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:keel.GraphInterKeel.datacf.visualizeData.VisualizePanelCharts2D.java

License:Open Source License

private void topdfjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_topdfjButtonActionPerformed
    // Save chart as a PDF file
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Save chart");
    KeelFileFilter fileFilter = new KeelFileFilter();
    fileFilter.addExtension("pdf");
    fileFilter.setFilterName("PDF images (.pdf)");
    chooser.setFileFilter(fileFilter);//from   ww  w  .  j  a  va  2  s .co  m
    chooser.setCurrentDirectory(Path.getFilePath());
    int opcion = chooser.showSaveDialog(this);
    Path.setFilePath(chooser.getCurrentDirectory());
    if (opcion == JFileChooser.APPROVE_OPTION) {
        String nombre = chooser.getSelectedFile().getAbsolutePath();
        if (!nombre.toLowerCase().endsWith(".pdf")) {
            // Add correct extension
            nombre += ".pdf";
        }
        File tmp = new File(nombre);
        if (!tmp.exists() || JOptionPane.showConfirmDialog(this,
                "File " + nombre + " already exists. Do you want to replace it?", "Confirm",
                JOptionPane.YES_NO_OPTION, 3) == JOptionPane.YES_OPTION) {
            try {
                Document document = new Document();
                PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(nombre));
                document.addAuthor("KEEL");
                document.addSubject("Attribute comparison");
                document.open();
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(550, 412);
                Graphics2D g2 = tp.createGraphics(550, 412, new DefaultFontMapper());
                Rectangle2D r2D = new Rectangle2D.Double(0, 0, 550, 412);
                chart2.setBackgroundPaint(Color.white);
                chart2.draw(g2, r2D);
                g2.dispose();
                cb.addTemplate(tp, 20, 350);
                document.close();
            } catch (Exception exc) {
            }
        }
    }
}

From source file:knop.psfj.exporter.PDFExporter.java

License:Open Source License

/**
 * Write single file report.// ww  w .java  2  s . c  o m
 *
 * @param frameList the frame list
 * @param path the path
 * @param page the page
 * @return the runnable
 */
public Runnable writeSingleFileReport(final BeadFrameList frameList, final String path, int page) {
    return new Runnable() {
        public void run() {

            Document document = null;
            PdfWriter writer = null;

            if (FileUtils.folderExists(path))
                FileUtils.deleteFile(path);

            try {
                document = new Document();

                writer = PdfWriter.getInstance(document, new FileOutputStream(path));
                document.open();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (DocumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (writer == null || document == null)
                return;

            for (BeadFrame frame : frameList) {

                //System.out.println("profile : " + frame);
                fillReport(document, writer, frame, frame.getId());
                document.newPage();
                incrementCount();
            }
            document.close();
            writer.close();
        }
    };

}

From source file:knop.psfj.exporter.PDFExporter.java

License:Open Source License

/**
 * Export bead image list.//from ww  w. j ava2  s .c  om
 *
 * @param imageList the image list
 * @param path the path
 */
public void exportBeadImageList(BeadFrameList imageList, String path) {
    Document document = new Document();
    try {

        int i = 0;
        int max = imageList.size();

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(path)));
        document.open();
        for (BeadFrame frame : imageList) {
            fillReport(document, writer, frame, frame.getId());

            setChanged();
            Integer progress = new Integer(100 * i++ / max);
            if (progress == 0)
                progress = 1;
            notifyObservers(new Message(this, "progress changed",
                    String.format("Generating bead PDF reports : %d/%d", i, max), progress));
            document.newPage();
        }

        document.close();
        writer.close();

        sendFinishMessage("Done.");

    } catch (FileNotFoundException e) {

        e.printStackTrace();
    } catch (DocumentException e) {

        e.printStackTrace();
        setChanged();
        notifyObservers(new Message("this", "error", "Error when generating PDF."));
    }
}

From source file:knop.psfj.exporter.PDFSumUpExporter.java

License:Open Source License

/**
 * Open document.//from w w w  .  j  a v  a2 s . c  om
 * 
 * @param path
 *           the path
 */
public void openDocument(String path) {
    currentDocument = new Document();

    try {

        if (FileUtils.folderExists(path))
            FileUtils.deleteFile(path);

        currentWriter = PdfWriter.getInstance(currentDocument, new FileOutputStream(path));
        currentDocument.open();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        currentWriter = null;
        currentDocument = null;
        e.printStackTrace();
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        currentWriter = null;
        currentDocument = null;
        e.printStackTrace();
    }

    if (currentWriter == null)
        manager.update(manager, new Message(manager, "error",
                "Error when creating the document. Please close your PDF reader before exporting this document."));

}

From source file:lmcpointofsalessystem.PDFCustomers.java

public PDFCustomers(String tblName) throws IOException {
    try {/*from   www .  j a  v a  2s  .  c o  m*/
        LMCPointofSalesSystem connect = new LMCPointofSalesSystem();
        con = connect.con;
        st = connect.s;
        Document document = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);

        PdfWriter.getInstance(document, new FileOutputStream(tblName + ".pdf"));
        document.open();
        Image image = Image.getInstance("src/lmcpointofsalessystem/Assets/header3.png");
        document.add(image);
        document.setMarginMirroring(true);

        PdfPTable newheaderTable;
        newheaderTable = getDatas(tblName);
        newheaderTable.setHorizontalAlignment(Element.ALIGN_CENTER);
        document.add(newheaderTable);
        document.close();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(PDFCustomers.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(PDFCustomers.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:lmcpointofsalessystem.PDFCustomersEmployee.java

public PDFCustomersEmployee(String tblName) throws IOException {
    try {//www.j  av a 2 s.c o m
        LMCPointofSalesSystem connect = new LMCPointofSalesSystem();
        con = connect.con;
        st = connect.s;
        Document document = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);

        PdfWriter.getInstance(document, new FileOutputStream(tblName + ".pdf"));
        document.open();
        Image image = Image.getInstance("src/lmcpointofsalessystem/Assets/header3.png");
        document.add(image);
        document.setMarginMirroring(true);

        PdfPTable newheaderTable;
        newheaderTable = getDatas(tblName);
        newheaderTable.setHorizontalAlignment(Element.ALIGN_CENTER);
        document.add(newheaderTable);
        document.close();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(PDFCustomersEmployee.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(PDFCustomersEmployee.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:lmcpointofsalessystem.PDFOrders.java

public PDFOrders(String tblName) throws IOException {
    try {/*from w ww  .  j  av a 2s .c  o  m*/
        LMCPointofSalesSystem connect = new LMCPointofSalesSystem();
        con = connect.con;
        st = connect.s;
        Document document = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);

        PdfWriter.getInstance(document, new FileOutputStream(tblName + ".pdf"));
        document.open();
        Image image = Image.getInstance("src/lmcpointofsalessystem/Assets/header3.png");
        document.add(image);
        document.setMarginMirroring(true);

        PdfPTable newheaderTable;
        newheaderTable = getDatas(tblName);
        newheaderTable.setHorizontalAlignment(Element.ALIGN_CENTER);
        document.add(newheaderTable);
        document.close();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(PDFEmployees.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(PDFEmployees.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:lt.bsprendimai.ddesk.pdf.PDFTicket.java

License:Apache License

public byte[] writePage() throws Exception {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    try {/*  w ww  . ja  v a 2s.com*/
        logo = Image.getInstance(root.getAbsolutePath() + "/logo.gif");
        logo.setAlignment(Image.ALIGN_LEFT);
    } catch (Exception exc) {
        exc.printStackTrace();
    }

    baseArial = BaseFont.createFont(root.getAbsolutePath() + "/objects/arial.ttf", BaseFont.CP1257,
            BaseFont.EMBEDDED);

    Document doc = new Document(PageSize.A4, 56.5354331f, 22.6771654f, 28.3464567f, 25.0f);
    PdfWriter.getInstance(doc, bout);

    doc.open();

    logo.setAbsolutePosition(28.3464567f, doc.getPageSize().height() - logo.height() - 25.0f);
    doc.add(logo);
    Paragraph pg = new Paragraph(sdf.format(new Date()), new Font(baseArial, 10));
    pg.setAlignment(Element.ALIGN_RIGHT);
    doc.add(pg);
    doc.add(new Phrase("\n\n\n"));

    writeClientInfo(doc);
    writeTicketInfo(doc);
    writeJobInfo(doc);
    writeWorkerInfo(doc);

    doc.close();

    return bout.toByteArray();
}

From source file:managedbean.aas.reportController.java

public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) {

    Document document = new Document();
    try {// w  w w . java2s  . com
        List<InputStream> pdfs = streamOfPDFFiles;
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }
        // Create a writer for the outputstream            
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
        // data

        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    cb.setFontAndSize(bf, 9);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
                            "" + currentPageNumber + " of " + totalPages, 520, 5, 0);
                    cb.endText();
                }
            }
            pageOfCurrentReaderPDF = 0;
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:mesquite.lib.MesquitePDFFile.java

License:Open Source License

/**
@arg s String holds the text that the pdf file will contain
@arg font java.awt.Font the font is specified this way for compatibility with the similar method in MesquitePrintJob
 *///from w  w  w . ja  v  a2s  .c  om
public void printText(String s, java.awt.Font font) {
    final String exceptionMessage = "Error, an exception occurred while creating the pdf text document: ";
    if (s == null || font == null)
        return;

    //do the translation from logical to physical font here      
    //currently, the only font this method ever gets called with is "Monospaced",PLAIN,10.  So the
    //translation effort here will be minimal      
    int desiredFontFamily; // "Monospaced" isn't defined in com.lowagie.text.Font
    if (font.getFamily().equals("Monospaced"))
        desiredFontFamily = com.lowagie.text.Font.COURIER;
    else
        desiredFontFamily = com.lowagie.text.Font.TIMES_ROMAN;
    com.lowagie.text.Font textFont;
    switch (font.getStyle()) {
    case java.awt.Font.BOLD: {
        textFont = new com.lowagie.text.Font(desiredFontFamily, font.getSize(), com.lowagie.text.Font.BOLD);
        break;
    }
    case java.awt.Font.ITALIC: {
        textFont = new com.lowagie.text.Font(desiredFontFamily, font.getSize(), com.lowagie.text.Font.ITALIC);
        break;
    }
    case java.awt.Font.PLAIN: {
        textFont = new com.lowagie.text.Font(desiredFontFamily, font.getSize(), com.lowagie.text.Font.NORMAL);
        break;
    }
    default: {
        textFont = new com.lowagie.text.Font(desiredFontFamily, font.getSize(),
                com.lowagie.text.Font.BOLDITALIC);
    }
    }
    document = new Document();
    try {
        PdfWriter.getInstance(document, new FileOutputStream(pdfPathString));
        addMetaData(document);
        document.open();
        document.add(new Paragraph(s, textFont));
    } catch (DocumentException de) {
        MesquiteTrunk.mesquiteTrunk.alert(exceptionMessage + de.getMessage());
    } catch (IOException ioe) {
        MesquiteTrunk.mesquiteTrunk.alert(exceptionMessage + ioe.getMessage());
    }
    this.end();
}