Example usage for com.lowagie.text.pdf PdfWriter getInstance

List of usage examples for com.lowagie.text.pdf PdfWriter getInstance

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfWriter getInstance.

Prototype


public static PdfWriter getInstance(Document document, OutputStream os) throws DocumentException 

Source Link

Document

Use this method to get an instance of the PdfWriter.

Usage

From source file:de.dhbw.humbuch.util.PDFHandler.java

/**
 * Creates a ByteArrayOutputStream which contains the PDF as a byte array.
 * // w w  w  .j a  va  2s  .  c  o  m
 * @return the byteArrayOutputStream the PDF is stored in, null if an error
 *         occurred.
 */
public ByteArrayOutputStream createByteArrayOutputStreamForPDF() {
    ByteArrayOutputStream byteArrayOutputStream;
    try {
        byteArrayOutputStream = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, byteArrayOutputStream);
        event = new HeaderFooter();
        writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
        writer.setPageEvent(event);

        this.document.open();
        this.addMetaData(document);
        int initialDocumentSize = writer.getCurrentDocumentSize();
        this.insertDocumentParts(document);

        if (byteArrayOutputStream.size() > 0 || writer.getCurrentDocumentSize() > initialDocumentSize) {
            this.document.close();
        } else {
            return null;
        }

        return byteArrayOutputStream;
    } catch (DocumentException e) {
        System.err.println("Could not create ByteArrayOutputStream of PDF data. " + e.getMessage());
    }

    return null;
}

From source file:de.intranda.test_ics.ImageHelper.java

License:Apache License

public void doGeneration(File[] imageFiles, File pdfFile)
        throws IOException, DocumentException, OutOfMemoryError {

    if (imageFiles.length > 0) {

        // allImages = reverseFileList(allImages);
        Document pdfDocument = null;
        @SuppressWarnings("unused")
        int pageCount = 1;
        PdfWriter pdfWriter = null;//from  w  ww  .  j a v a2 s  .  c  o m

        pdfDocument = new Document();
        FileOutputStream outputPdfFile = new FileOutputStream(pdfFile);
        pdfWriter = PdfWriter.getInstance(pdfDocument, outputPdfFile);
        pdfDocument.open();

        for (File imageFile : imageFiles) {
            addPage(imageFile, pdfWriter, pdfDocument, 1, 0);
            pageCount++;
        }

        pdfDocument.close();
        pdfWriter.close();
        try {
            if (outputPdfFile != null) {
                outputPdfFile.close();
            }
        } catch (IOException e) {
            LOGGER.warn("Error on closing fileoutputstream");
        }
    }
}

From source file:de.ipbhalle.metfrag.tools.renderer.WritePDFTable.java

License:Open Source License

/**
 * Instantiates a new write pdf table. This is mainly for debugging the gasteiger marsili charges
 * /*from ww  w.j av  a2s  .com*/
 * @param odir the odir
 * @param width the width
 * @param height the height
 * @param chargeResults the charge results
 */
public WritePDFTable(String odir, int width, int height, List<ChargeResult> chargeResults) {

    this.width = width;
    this.height = height;

    try {
        File file = new File(odir);
        document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));

        float[] widths = new float[ncol];
        for (int i = 0; i < ncol; i += 3) {
            widths[i] = 2.5f;
            widths[i + 1] = 0.75f;
            widths[i + 2] = 0.75f;
        }
        table = new PdfPTable(widths);
        document.open();

        boolean drawPartialCharges = true;

        for (ChargeResult result : chargeResults) {

            if (drawPartialCharges) {
                PdfPCell cellBonds = new PdfPCell();
                PdfPCell cellBondsDist = new PdfPCell();
                Phrase phraseBonds = new Phrase();
                Phrase phraseBondsDist = new Phrase();

                com.lowagie.text.Image image = com.lowagie.text.Image
                        .getInstance(writeMOL2PNGFile(result.getOriginalMol()).getAbsolutePath());
                image.setAbsolutePosition(0, 0);
                table.addCell(image);

                String stringAtoms = "";
                String stringAtomsCharge = "";
                for (IAtom atom : result.getOriginalMol().atoms()) {
                    if (!atom.getSymbol().equals("H") && !atom.getSymbol().equals("C")) {
                        stringAtoms += atom.getSymbol() + (Integer.parseInt(atom.getID()) + 1) + "\n";
                        stringAtomsCharge += Math.round(atom.getCharge() * 100.0) / 100.0 + "\n";
                    }
                }

                addProperty(phraseBonds, stringAtoms);
                addProperty(phraseBondsDist, stringAtomsCharge);
                cellBonds.addElement(phraseBonds);
                cellBondsDist.addElement(phraseBondsDist);
                table.addCell(cellBonds);
                table.addCell(cellBondsDist);
                drawPartialCharges = false;
            }

            PdfPCell cellBonds = new PdfPCell();
            PdfPCell cellBondsDist = new PdfPCell();
            Phrase phraseBonds = new Phrase();
            Phrase phraseBondsDist = new Phrase();

            com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(
                    writeMOL2PNGFile(result.getOriginalMol(), result.getMolWithProton()).getAbsolutePath());
            image.setAbsolutePosition(0, 0);
            table.addCell(image);

            String stringPDFBonds = "";
            String stringPDFBondsDist = "";
            String[] lines = result.getChargeString().split("\n");
            for (int i = 0; i < lines.length; i++) {
                boolean carbonHydrogenBond = lines[i].matches("[A-Z]+[0-9]+-H[0-9]+.*");
                if (!carbonHydrogenBond) {
                    String[] linesArr = lines[i].split("\t");
                    stringPDFBondsDist += linesArr[1] + "\n";
                    stringPDFBonds += linesArr[0] + "\n";
                }
            }

            addProperty(phraseBonds, stringPDFBonds);
            addProperty(phraseBondsDist, stringPDFBondsDist);
            cellBonds.addElement(phraseBonds);
            cellBondsDist.addElement(phraseBondsDist);
            table.addCell(cellBonds);
            table.addCell(cellBondsDist);
        }

        document.add(table);
        document.close();

    } catch (Exception exc) {
        exc.printStackTrace();
    }
}

From source file:de.japes.text.PdfCreator.java

License:Open Source License

public String exportToPdf(byte[] imgArray) {

    String filename;//from   ww  w.ja  v  a  2 s .c o  m
    Document document = new Document();
    Image img = null;

    Calendar cal = Calendar.getInstance();

    filename = "chart_" + cal.get(Calendar.YEAR) + cal.get(Calendar.MONTH) + cal.get(Calendar.DAY_OF_MONTH)
            + "_" + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.MINUTE) + ".pdf";

    try {
        img = Image.getInstance(imgArray);
    } catch (MalformedURLException e) {
        return e.getMessage();
    } catch (IOException e) {
        return e.getMessage();
    } catch (BadElementException e) {
        return e.getMessage();
    }

    img.setAlignment(Image.ALIGN_CENTER);

    try {

        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file

        PdfWriter.getInstance(document, new FileOutputStream(filename));

        // step 3: we open the document
        document.open();

        // step 4: we add a paragraph to the document
        document.add(img);

    } catch (DocumentException de) {
        return de.getMessage();
    } catch (IOException ioe) {
        return ioe.getMessage();
    }

    // step 5: we close the document
    document.close();

    return filename;
}

From source file:de.jdufner.sudoku.generator.pdf.PdfPrinterImpl.java

License:Open Source License

@Override
public void printFrontpage(String name, List<PdfSolution> solutions, String fileName)
        throws DocumentException, FileNotFoundException {
    Document document = new Document(PageSize.A4, 10, 10, 10, 10);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    writeFrontpage(name, document, solutions);
    writer.close();//  w ww .  j a  v  a  2  s.c o m
}

From source file:de.jdufner.sudoku.generator.pdf.PdfPrinterImpl.java

License:Open Source License

@Override
public void printQuests(List<SudokuData> sudokus, String fileName)
        throws DocumentException, FileNotFoundException {
    Document document = new Document(PageSize.A4, 10, 10, 10, 10);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    writeDocument(document, sudokus);/*  w  w w  . java 2s.com*/
    writer.close();
}

From source file:de.jdufner.sudoku.generator.pdf.PdfPrinterImpl.java

License:Open Source License

@Override
public void printResults(List<SudokuData> sudokus, String fileName)
        throws DocumentException, FileNotFoundException {
    Document document = new Document(PageSize.A4, 10, 10, 10, 10);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    writeDocument(document, sudokus);//from  w  ww.j  a v  a 2 s.  c  om
    writer.close();
}

From source file:de.maklerpoint.office.Schnittstellen.PDF.ExportListePDF.java

License:Open Source License

public void write() throws DocumentException, FileNotFoundException {

    SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm");

    Document doc = null;//  ww w. j  a  va 2 s  .c  o m

    if (titles.length > 7)
        doc = new Document(PageSize.A4.rotate(), 20, 20, 20, 20);
    else
        doc = new Document(PageSize.A4, 20, 20, 20, 20);

    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(filename));
    doc.addAuthor("MaklerPoint - www.maklerpoint.de");
    doc.addCreator("MaklerPoint - www.maklerpoint.de");
    doc.addCreationDate();
    doc.addTitle(title);

    doc.open();

    doc.add(new Paragraph(title, FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, Color.BLACK)));

    Table t = new Table(titles.length, data.length + 1);
    t.setPadding(3);
    t.setSpacing(0);
    t.setBorderWidth(1);

    for (int i = 0; i < titles.length; i++) {
        Cell c1 = new Cell(titles[i]);
        c1.setHeader(true);
        t.addCell(c1);
    }
    t.endHeaders();

    for (int i = 0; i < data.length; i++) {
        for (int j = 0; j < data[i].length; j++) {
            Cell c1 = null;
            if (data[i][j] != null)
                c1 = new Cell(data[i][j].toString());
            else
                c1 = new Cell("");
            t.addCell(c1);
        }
    }

    doc.add(t);

    if (footer == null) {
        doc.add(new Paragraph(
                ("Export " + title + " - Genereriert am " + df.format(new Date(System.currentTimeMillis())))
                        + " von MaklerPoint",
                FontFactory.getFont(FontFactory.TIMES, 10, Font.NORMAL, Color.black)));
    } else {
        doc.add(new Paragraph(footer, FontFactory.getFont(FontFactory.TIMES, 10, Font.NORMAL, Color.black)));
    }

    doc.close();
}

From source file:de.sub.goobi.forms.ProzessverwaltungForm.java

License:Open Source License

/**
 * Generate result as PDF./*  ww  w .  jav a 2 s.  c o m*/
 */
public void generateResultAsPdf() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.getResponseComplete()) {

        /*
         * Vorbereiten der Header-Informationen
         */
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        try {
            ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
            String contentType = servletContext.getMimeType("search.pdf");
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment;filename=\"search.pdf\"");
            ServletOutputStream out = response.getOutputStream();

            SearchResultGeneration sr = new SearchResultGeneration(this.filter, this.showClosedProcesses,
                    this.showArchivedProjects);
            HSSFWorkbook wb = sr.getResult();
            List<List<HSSFCell>> rowList = new ArrayList<>();
            HSSFSheet mySheet = wb.getSheetAt(0);
            Iterator<Row> rowIter = mySheet.rowIterator();
            while (rowIter.hasNext()) {
                HSSFRow myRow = (HSSFRow) rowIter.next();
                Iterator<Cell> cellIter = myRow.cellIterator();
                List<HSSFCell> row = new ArrayList<>();
                while (cellIter.hasNext()) {
                    HSSFCell myCell = (HSSFCell) cellIter.next();
                    row.add(myCell);
                }
                rowList.add(row);
            }
            Document document = new Document();
            Rectangle a4quer = new Rectangle(PageSize.A3.getHeight(), PageSize.A3.getWidth());
            PdfWriter.getInstance(document, out);
            document.setPageSize(a4quer);
            document.open();
            if (rowList.size() > 0) {
                Paragraph p = new Paragraph(rowList.get(0).get(0).toString());
                document.add(p);
                PdfPTable table = new PdfPTable(9);
                table.setSpacingBefore(20);
                for (List<HSSFCell> row : rowList) {
                    for (HSSFCell hssfCell : row) {
                        // TODO aufhbschen und nicht toString() nutzen
                        String stringCellValue = hssfCell.toString();
                        table.addCell(stringCellValue);
                    }
                }
                document.add(table);
            }

            document.close();
            out.flush();
            facesContext.responseComplete();
        } catch (Exception e) {
            logger.error(e);
        }
    }
}

From source file:de.thorstenberger.examServer.webapp.action.SystemConfigSubmitAction.java

License:Open Source License

/**
 * @param mapping/*from w w  w.  j a v  a2  s.  com*/
 * @param request
 * @param response
 * @param configManager
 * @return
 */
private ActionForward createSignedPDF(final ActionMapping mapping, final HttpServletRequest request,
        final HttpServletResponse response, final ConfigManager configManager) {
    final ActionErrors errors = new ActionErrors();
    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        final Document pdf = new Document();
        PdfWriter.getInstance(pdf, baos);
        pdf.open();
        pdf.add(new Paragraph("Signaturtest."));
        pdf.close();

        final InputStream pdfIn = new ByteArrayInputStream(baos.toByteArray());
        baos.reset();
        SignPdf.signAndTimestamp(pdfIn, baos, configManager.getPDFSignatureInfos());
        // write signed pdf to response
        response.setContentType("application/pdf");
        // set an appropriate filename
        response.setHeader("Content-Disposition", "attachment; filename=signaturetest.pdf");
        response.getOutputStream().write(baos.toByteArray());
        return null;
    } catch (final DocumentException e) {
        addError(errors, e);
    } catch (final IOException e) {
        addError(errors, e);
    } catch (final SignatureException e) {
        addError(errors, e);
    } catch (final KeyStoreException e) {
        addError(errors, e);
    }
    saveMessages(request, errors);
    return mapping.findForward("success");
}