Example usage for com.itextpdf.text Rectangle Rectangle

List of usage examples for com.itextpdf.text Rectangle Rectangle

Introduction

In this page you can find the example usage for com.itextpdf.text Rectangle Rectangle.

Prototype

public Rectangle(final float urx, final float ury) 

Source Link

Document

Constructs a Rectangle -object starting from the origin (0, 0).

Usage

From source file:org.primaresearch.pdf.PageToPdfConverter.java

License:Apache License

/**
 * Converts a list of pages to PDF/*from   w  ww  .j  a  v a  2 s . co m*/
 * @param pages
 * @param imageFiles
 * @param targetPdf
 */
public void convert(List<Page> pages, List<String> imageFiles, String targetPdf) {

    Document document = null;
    try {
        PdfWriter writer = null;

        //Add pages
        createFont();
        boolean addPageBreak = false;
        for (int i = 0; i < pages.size(); i++) {
            if (document == null) {
                document = new Document(new Rectangle(pages.get(i).getLayout().getWidth(),
                        pages.get(i).getLayout().getHeight()));
                writer = PdfWriter.getInstance(document, new FileOutputStream(targetPdf));
                document.open();
            }
            addPage(writer, document, pages.get(i), imageFiles.get(i), addPageBreak);
            addPageBreak = true;
        }
    } catch (Exception exc) {
        exc.printStackTrace();
    } finally {
        document.close();
    }
}

From source file:org.primaresearch.pdf.PageToPdfConverter.java

License:Apache License

/**
 * Converts a single page to PDF// w w w  .  jav a2s .co m
 * @param page
 * @param imageFile
 * @param targetPdf
 */
public void convert(Page page, String imageFile, String targetPdf) {
    Document document = new Document(new Rectangle(page.getLayout().getWidth(), page.getLayout().getHeight()));
    try {
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(targetPdf));
        document.open();

        createFont();
        addPage(writer, document, page, imageFile, false);
    } catch (Exception exc) {
        exc.printStackTrace();
    } finally {
        document.close();
    }
}

From source file:org.primaresearch.pdf.PageToPdfConverter.java

License:Apache License

/**
 * Adds a page to the PDF/*from  w  w  w .j a v  a  2s .com*/
 * @param writer
 * @param doc
 * @param page
 * @param imageFile
 * @param addPageBreak
 */
private void addPage(PdfWriter writer, Document doc, Page page, String imageFile, boolean addPageBreak) {
    try {

        if (addPageBreak) {
            doc.setPageSize(new Rectangle(page.getLayout().getWidth(), page.getLayout().getHeight()));
            doc.newPage();
        }

        //TODO Use image DPI and size
        //The measurement unit of the PDF is point (1 Point = 0.0352777778 cm)
        //For now: Set the PDF size to the PAGE size (1px = 1pt)
        //PDPage pdfPage = new PDPage(PDPage.PAGE_SIZE_A4); 
        /*PDPage pdfPage = new PDPage(new PDRectangle(page.getLayout().getWidth(), page.getLayout().getHeight()));
        doc.addPage( pdfPage );
                
        if (DEBUG) {
           System.out.println("Mediabox width: "+pdfPage.getMediaBox().getWidth());
           System.out.println("Mediabox height: "+pdfPage.getMediaBox().getHeight());
        }
                
                
        // Start a new content stream which will "hold" the to be created content
        PDPageContentStream contentStream = new PDPageContentStream(doc, pdfPage);
        */
        try {
            addText(writer, page);
            addImage(imageFile, writer, doc, page); //The images hides the text
            if (addRegionOutlines)
                addOutlines(writer, page, null);
            if (addTextLineOutlines)
                addOutlines(writer, page, LowLevelTextType.TextLine);
            if (addWordOutlines)
                addOutlines(writer, page, LowLevelTextType.Word);
            if (addGlyphOutlines)
                addOutlines(writer, page, LowLevelTextType.Glyph);
        } finally {
            // Make sure that the content stream is closed:
            //contentStream.close();
        }
    } catch (Exception exc) {
        exc.printStackTrace();
    }

}

From source file:org.ujmp.itext.ExportPDF.java

License:Open Source License

public static final void save(File file, Component c, int width, int height) {
    if (file == null) {
        logger.log(Level.WARNING, "no file selected");
        return;//from   w  w  w . ja  v  a  2 s.c o m
    }
    if (c == null) {
        logger.log(Level.WARNING, "no component provided");
        return;
    }
    try {
        Document document = new Document(new Rectangle(width, height));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file.getAbsolutePath()));
        document.addAuthor("UJMP v" + UJMP.UJMPVERSION);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2 = new PdfGraphics2D(cb, width, height, new DefaultFontMapper());
        if (c instanceof CanRenderGraph) {
            ((CanRenderGraph) c).renderGraph(g2);
        } else {
            c.paint(g2);
        }
        g2.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();
        writer.close();
    } catch (Exception e) {
        logger.log(Level.WARNING, "could not save PDF file", e);
    }
}

From source file:pdfcreator.PDFCreator.java

License:Open Source License

@SuppressWarnings("static-access")
protected void createPdf(String filename, String[] images) throws Exception {
    Document doc = new Document();
    PdfWriter writer;/*from  w  w  w  .  j a v a 2 s . com*/

    if (pdfxConformance.equals("PDFA1A")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_1A);
    } else if (pdfxConformance.equals("PDFA1B")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_1B);
    } else if (pdfxConformance.equals("PDFA2A")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_2A);
    } else if (pdfxConformance.equals("PDFA2B")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_2B);
    } else if (pdfxConformance.equals("PDFA3A")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_3A);
    } else if (pdfxConformance.equals("PDFA3B")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_3B);
    } else {
        writer = PdfWriter.getInstance(doc, new FileOutputStream(filename));
    }

    if (pdfVersion.equals("1.4")) {
        writer.setPdfVersion(PdfWriter.VERSION_1_4);
    } else if (pdfVersion.equals("1.5")) {
        writer.setPdfVersion(PdfWriter.VERSION_1_5);
    } else if (pdfVersion.equals("1.6")) {
        writer.setPdfVersion(PdfWriter.VERSION_1_6);
    } else if (pdfVersion.equals("1.7")) {
        writer.setPdfVersion(PdfWriter.VERSION_1_7);
    } else {
        writer.setPdfVersion(PdfWriter.VERSION_1_4);
    }

    verbose(filename + ": open");

    doc.addCreationDate();
    doc.addCreator(creator);

    if (title != null) {
        doc.addTitle(title);
    }

    for (int i = 0; i < images.length; i++) {
        verbose(" +" + images[i]);

        Image img = Image.getInstance(images[i]);

        doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
        doc.setMargins(0, 0, 0, 0);

        if (doc.isOpen()) {
            doc.newPage();
        } else {
            doc.open();
        }

        doc.add(img);

        doc.newPage();
    }

    ICC_Profile icc = getImageColorProfile(images[0]);

    if (icc == null) {
        System.err.println("warning: no color profile available in " + images[0] + " using " + profileName);
        icc = getDefaultColorProfile();
    }

    writer.setOutputIntents("Custom", "", null, null, icc);

    writer.createXmpMetadata();

    doc.close();

    verbose(filename + ": close");
}

From source file:pl.marcinmilkowski.hocrtopdf.Main.java

License:Open Source License

/**
 * @param args/*from w w w. j a  v a  2  s .c  o m*/
 */
public static void main(String[] args) {
    try {
        if (args.length < 1 || args[0] == "--help" || args[0] == "-h") {
            System.out.print("Usage: java pl.marcinmilkowski.hocrtopdf.Main INPUTURL.html OUTPUTURL.pdf\n"
                    + "\n" + "Converts hOCR files into PDF\n" + "\n"
                    + "Example: java pl.marcinmilkowski.hocrtopdf.Main hocr.html output.pdf\n");
            if (args.length < 1)
                System.exit(-1);
            else
                System.exit(0);
        }
        URL inputHOCRFile = null;
        FileOutputStream outputPDFStream = null;
        try {
            File file = new File(args[0]);
            inputHOCRFile = file.toURI().toURL();
        } catch (MalformedURLException e) {
            System.out.println("The first parameter has to be a valid file.");
            System.out.println("We got an error: " + e.getMessage());
            System.exit(-1);
        }
        try {
            outputPDFStream = new FileOutputStream(args[1]);
        } catch (FileNotFoundException e) {
            System.out.println("The second parameter has to be a valid URL");
            System.exit(-1);
        }

        // The resolution of a PDF file (using iText) is 72pt per inch
        float pointsPerInch = 72.0f;

        // Using the jericho library to parse the HTML file
        Source source = new Source(inputHOCRFile);

        int pageCounter = 1;

        Document pdfDocument = null;
        PdfWriter pdfWriter = null;
        PdfContentByte cb = null;
        RandomAccessFileOrArray ra = null;

        // Find the tag of class ocr_page in order to load the scanned image
        StartTag pageTag = source.getNextStartTag(0, "class", OCRPAGE);
        while (pageTag != null) {
            int prevPos = pageTag.getEnd();
            Pattern imagePattern = Pattern.compile("image\\s+([^;]+)");
            Matcher imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title"));
            if (!imageMatcher.find()) {
                System.out.println("Could not find a tag of class \"ocr_page\", aborting.");
                System.exit(-1);
            }
            // Load the image
            Image pageImage = null;
            try {
                File file = new File(imageMatcher.group(1));
                pageImage = Image.getInstance(file.toURI().toURL());
            } catch (MalformedURLException e) {
                System.out.println("Could not load the scanned image from: " + "file://" + imageMatcher.group(1)
                        + ", aborting.");
                System.exit(-1);
            }
            if (pageImage.getOriginalType() == Image.ORIGINAL_TIFF) { // this might
                                                                      // be
                                                                      // multipage
                                                                      // tiff!
                File file = new File(imageMatcher.group(1));
                if (pageCounter == 1 || ra == null) {
                    ra = new RandomAccessFileOrArray(file.toURI().toURL());
                }
                int nPages = TiffImage.getNumberOfPages(ra);
                if (nPages > 0 && pageCounter <= nPages) {
                    pageImage = TiffImage.getTiffImage(ra, pageCounter);
                }
            }
            int dpiX = pageImage.getDpiX();
            if (dpiX == 0) { // for images that don't set the resolution we assume
                             // 300 dpi
                dpiX = 300;
            }
            int dpiY = pageImage.getDpiY();
            if (dpiY == 0) { // as above for dpiX
                dpiY = 300;
            }
            float dotsPerPointX = dpiX / pointsPerInch;
            float dotsPerPointY = dpiY / pointsPerInch;
            float pageImagePixelHeight = pageImage.getHeight();
            if (pdfDocument == null) {
                pdfDocument = new Document(new Rectangle(pageImage.getWidth() / dotsPerPointX,
                        pageImage.getHeight() / dotsPerPointY));
                pdfWriter = PdfWriter.getInstance(pdfDocument, outputPDFStream);
                pdfDocument.open();
                // Put the text behind the picture (reverse for debugging)
                // cb = pdfWriter.getDirectContentUnder();
                cb = pdfWriter.getDirectContent();
            } else {
                pdfDocument.setPageSize(new Rectangle(pageImage.getWidth() / dotsPerPointX,
                        pageImage.getHeight() / dotsPerPointY));
                pdfDocument.newPage();
            }
            // first define a standard font for our text
            BaseFont base = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED);
            Font defaultFont = new Font(base, 8);
            // FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD,
            // CMYKColor.BLACK);

            cb.setHorizontalScaling(1.0f);

            pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY);
            pageImage.setAbsolutePosition(0, 0);
            // Put the image in front of the text (reverse for debugging)
            // pdfWriter.getDirectContent().addImage(pageImage);
            pdfWriter.getDirectContentUnder().addImage(pageImage);

            // In order to place text behind the recognised text snippets we are
            // interested in the bbox property
            Pattern bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}");
            // This pattern separates the coordinates of the bbox property
            Pattern bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)");
            // Only tags of the ocr_line class are interesting
            StartTag ocrTag = source.getNextStartTag(prevPos, "class", OCRPAGEORLINE);
            while (ocrTag != null) {
                prevPos = ocrTag.getEnd();
                if ("ocrx_word".equalsIgnoreCase(ocrTag.getAttributeValue("class"))) {
                    net.htmlparser.jericho.Element lineElement = ocrTag.getElement();
                    Matcher bboxMatcher = bboxPattern.matcher(lineElement.getAttributeValue("title"));
                    if (bboxMatcher.find()) {
                        // We found a tag of the ocr_line class containing a bbox property
                        Matcher bboxCoordinateMatcher = bboxCoordinatePattern.matcher(bboxMatcher.group());
                        bboxCoordinateMatcher.find();
                        int[] coordinates = { Integer.parseInt((bboxCoordinateMatcher.group(1))),
                                Integer.parseInt((bboxCoordinateMatcher.group(2))),
                                Integer.parseInt((bboxCoordinateMatcher.group(3))),
                                Integer.parseInt((bboxCoordinateMatcher.group(4))) };
                        String line = lineElement.getContent().getTextExtractor().toString();
                        float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX;
                        float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY;

                        // Put the text into the PDF
                        cb.beginText();
                        // Comment the next line to debug the PDF output (visible Text)
                        cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
                        // height
                        cb.setFontAndSize(defaultFont.getBaseFont(), Math.max(Math.round(bboxHeightPt), 1));
                        // width
                        cb.setHorizontalScaling(bboxWidthPt / cb.getEffectiveStringWidth(line, false));
                        cb.moveText((coordinates[0] / dotsPerPointX),
                                ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY));
                        cb.showText(line);
                        cb.endText();
                        cb.setHorizontalScaling(1.0f);
                    }
                } else {
                    if ("ocr_page".equalsIgnoreCase(ocrTag.getAttributeValue("class"))) {
                        pageCounter++;
                        pageTag = ocrTag;
                        break;
                    }
                }
                ocrTag = source.getNextStartTag(prevPos, "class", OCRPAGEORLINE);
            }
            if (ocrTag == null) {
                pdfDocument.close();
                break;
            }
        }
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:procuracoes.classes.Digitalizacao.java

public void salva(String user) throws MorenaException, SQLException {

    source = TwainManager.selectSource(null);
    npag = 0;// w  ww .j  a v  a2  s .  c  o m

    if (source != null) {
        morenaImage = new MorenaImage(source); //cria um objeto MorenaImage que manipula a imagem direta do scanner
        image = Toolkit.getDefaultToolkit().createImage(morenaImage); //cria um objeto Image para receber a imagem
        i.add(npag, image);
        bimg = new BufferedImage(morenaImage.getWidth(), //cria um bufferedImage para poder salvar a imagem
                morenaImage.getHeight(), BufferedImage.TYPE_INT_RGB);

        g = bimg.createGraphics();//cria um graphics2d para manipular a imagem do buffer
        g.drawImage(i.get(npag), 0, 0, null);//desenha o objeto Image no BufferedImage
        try {
            ImageIO.write(bimg, "jpg", new File("C:/temp/teste" + Integer.toString(npag) + ".jpg")); //Cria um novo arquivo jpg; 
            s.add("C:/temp/teste" + Integer.toString(npag) + ".jpg"); //Se a pasta no existir, a converso no funciona;
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Erro ao salvar imagem " + ex);
        }
        //---------------------------------------//
        JFrame f = new JFrame();
        f.setBounds(50, 200, 1500, 600);
        f.setTitle("Visualizador");
        f.setMaximumSize(new Dimension(1500, 600));
        f.setMinimumSize(new Dimension(1500, 600));

        cx = 0;
        cy = 0;

        resizedImg = new BufferedImage(100, 150, BufferedImage.TYPE_INT_ARGB);
        g2 = resizedImg.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(i.get(npag), 0, 0, 100, 150, null);
        g2.dispose();

        x = new JLabel(new ImageIcon(resizedImg));

        GridBagLayout grid = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        GridBagConstraints d = new GridBagConstraints();

        c.fill = GridBagConstraints.HORIZONTAL;
        d.gridheight = 8;
        d.gridwidth = 3;
        c.ipadx = 10;
        c.ipady = 10;
        c.gridx = cx;
        c.gridy = cy;

        d.gridheight = 0;
        d.gridwidth = 3;
        d.fill = GridBagConstraints.VERTICAL;
        d.anchor = d.PAGE_END;
        d.gridy = 5;

        f.setLayout(grid);
        f.add(new JLabel("Deseja continuar escaniando?"), d);

        JButton j1 = new JButton("Sim");
        j1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                morenaImage = new MorenaImage(source); //cria um objeto MorenaImage que manipula a imagem direta do scanner
                image = Toolkit.getDefaultToolkit().createImage(morenaImage); //cria um objeto Image para receber a imagem
                i.add(npag, image);
                bimg = new BufferedImage(morenaImage.getWidth(), //cria um bufferedImage para poder salvar a imagem
                        morenaImage.getHeight(), BufferedImage.TYPE_INT_RGB);

                g = bimg.createGraphics(); //cria um graphics2d para manipular a imagem do buffer
                g.drawImage(i.get(npag), 0, 0, null);
                //desenha o objeto Image no BufferedImage
                try {
                    ImageIO.write(bimg, "jpg", new File("C:/temp/teste" + Integer.toString(npag) + ".jpg")); //Cria um novo arquivo jpg;
                    s.add("C:/temp/teste" + Integer.toString(npag) + ".jpg");
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(null, "Erro ao salvar imagem " + ex);
                }
                //--------------------------------------------//
                resizedImg = new BufferedImage(100, 150, BufferedImage.TYPE_INT_ARGB);
                g2 = resizedImg.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g2.drawImage(i.get(npag), 0, 0, 100, 150, null);
                g2.dispose();

                if (npag < 8) {
                    cx = npag;
                } else if (npag >= 24) {
                    cx = npag - 24;
                    cy = 3;
                } else if (npag >= 16) {
                    cx = npag - 16;
                    cy = 2;
                } else if (npag >= 8) {
                    cx = npag - 8;
                    cy = 1;
                }

                x = new JLabel(new ImageIcon(resizedImg));
                c.gridx = cx;
                c.gridy = cy;

                f.add(x, c);
                f.validate();
                //----------------------------------------------//
                npag++;
            }
        });
        f.add(j1, d);

        JButton j2 = new JButton("Nao");
        j2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Document document = new Document();
                Rectangle r = new Rectangle(morenaImage.getWidth(), morenaImage.getHeight());
                document.setPageSize(r);
                try {
                    String output = getNovoCaminho();
                    FileOutputStream fos = new FileOutputStream(output);
                    PdfWriter writer = PdfWriter.getInstance(document, fos);
                    writer.open();
                    document.open();
                    int j = 0;
                    while (j < npag) {
                        document.add(com.itextpdf.text.Image.getInstance(s.get(j)));
                        j++;
                    }

                    document.close();
                    writer.close();
                } catch (DocumentException | IOException | SQLException ex) {
                    JOptionPane.showMessageDialog(null, "Erro ao criar arquivo pdf " + ex);
                }
                try {
                    TwainManager.close();
                    InsereProc in;
                    in = new InsereProc(user);
                    in.setVisible(true);
                    f.dispose();
                } catch (SQLException | TwainException ex) {
                    Logger.getLogger(Digitalizacao.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        f.add(j2, d);
        f.add(x, c);

        npag++;
        f.validate();
        f.setVisible(true);
        f.toFront();
    } else {
        JOptionPane.showMessageDialog(null, "Documneto nao encontrado !");
    }
}

From source file:projet_drone.InterfaceFinal.java

private void PDF() throws DocumentException, FileNotFoundException {

    // Dfinir la taille des page
    Rectangle pagesize = new Rectangle(516f, 1020f);
    Document document = new Document(pagesize, 36f, 72f, 18f, 18f);
    // Cration du fichier PDF
    PdfWriter.getInstance(document, new FileOutputStream("contrat.pdf"));
    // Ouvrir le fichier cr
    document.open();//from   w  w w  .  j  a  va2s .c  om
    // Ecrire dans le fichier PDF

    document.add(new Paragraph(ch));
    // Fermer le document,  ne pas oublier
    document.close();

}

From source file:ptolemy.vergil.basic.export.itextpdf.ExportPDFAction.java

License:Open Source License

/** Export PDF to a file.
 *  This uses the iText library at http://itextpdf.com/.
 *
 *  <p>If {@link ptolemy.gui.PtGUIUtilities#useFileDialog()} returns true
 *  then a java.awt.FileDialog is used, otherwise a javax.swing.JFileChooser
 *  is used.</p>//w w w. ja v a2s.  c om
 */
private void _exportPDF() {
    Dimension size = _frame.getContentSize();
    Rectangle pageSize = null;
    try {
        pageSize = new Rectangle(size.width, size.height);
    } catch (Throwable ex) {
        // This exception will occur if the iText library is not installed.
        MessageHandler.error("iText library is not installed. See http://itextpdf.com/."
                + "  You must have iText.jar in your classpath.  Sometimes, "
                + "iText.jar may be found in $PTII/vendors/itext/iText.jar.", ex);
        return;
    }
    Document document = new Document(pageSize);
    JFileChooserBugFix jFileChooserBugFix = new JFileChooserBugFix();
    Color background = null;
    PtFileChooser ptFileChooser = null;
    try {
        background = jFileChooserBugFix.saveBackground();

        ptFileChooser = new PtFileChooser(_frame, "Specify a pdf file to be written.",
                JFileChooser.SAVE_DIALOG);

        LinkedList extensions = new LinkedList();
        extensions.add("pdf");
        ptFileChooser.addChoosableFileFilter(new ExtensionFilenameFilter(extensions));

        BasicGraphFrame basicGraphFrame = null;
        if (_frame instanceof BasicGraphFrame) {
            basicGraphFrame = (BasicGraphFrame) _frame;
            ptFileChooser.setCurrentDirectory(basicGraphFrame.getLastDirectory());
            ptFileChooser.setSelectedFile(new File(basicGraphFrame.getModel().getName() + ".pdf"));
        }
        int returnVal = ptFileChooser.showDialog(_frame, "Export PDF");

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            if (basicGraphFrame != null) {
                basicGraphFrame.setLastDirectory(ptFileChooser.getCurrentDirectory());
            }
            File pdfFile = ptFileChooser.getSelectedFile().getCanonicalFile();

            if (pdfFile.getName().indexOf(".") == -1) {
                // If the user has not given the file an extension, add it
                pdfFile = new File(pdfFile.getAbsolutePath() + ".pdf");
            }

            // The Mac OS X FileDialog will ask if we want to save before this point.
            if (pdfFile.exists() && !PtGUIUtilities.useFileDialog()) {
                if (!MessageHandler.yesNoQuestion("Overwrite " + pdfFile.getName() + "?")) {
                    return;
                }
            }

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
            // To ensure Latex compatibility, use earlier PDF version.
            writer.setPdfVersion(PdfWriter.VERSION_1_3);
            document.open();
            PdfContentByte contentByte = writer.getDirectContent();

            PdfTemplate template = contentByte.createTemplate(size.width, size.height);
            Graphics2D graphics = template.createGraphics(size.width, size.height);
            template.setWidth(size.width);
            template.setHeight(size.height);

            Paper paper = new Paper();
            paper.setSize(size.width, size.height);
            paper.setImageableArea(0.0, 0.0, size.width, size.height);
            PageFormat format = new PageFormat();
            format.setPaper(paper);
            ((Printable) _frame).print(graphics, format, 0);
            graphics.dispose();
            contentByte.addTemplate(template, 0, 0);

            // Open the PDF file.
            // FIXME: _read is protected in BasicGraphFrame
            //_read(pdfFile.toURI().toURL());
            // Open the image pdfFile.
            if (basicGraphFrame == null) {
                MessageHandler.message("PDF file exported to " + pdfFile.getName());
                /* Remove the following. The extra click is annoying...
                } else {
                if (MessageHandler.yesNoQuestion("Open \""
                        + pdfFile.getCanonicalPath() + "\" in a browser?")) {
                    Configuration configuration = basicGraphFrame
                            .getConfiguration();
                    try {
                        URL imageURL = new URL(pdfFile.toURI().toURL()
                                .toString()
                                + "#in_browser");
                        configuration.openModel(imageURL, imageURL,
                                imageURL.toExternalForm(),
                                BrowserEffigy.staticFactory);
                    } catch (Throwable throwable) {
                        MessageHandler.error(
                                "Failed to open \"" + pdfFile.getName()
                                        + "\".", throwable);
                    }
                }
                 */
            }
        }
    } catch (Exception e) {
        MessageHandler.error("Export to PDF failed", e);
    } finally {
        try {
            document.close();
        } finally {
            jFileChooserBugFix.restoreBackground(background);
        }
    }
}

From source file:py.com.palermo.imprimeetiquetas.web.ProductoController.java

public String createPdf() throws IOException, DocumentException {

    if (hayParaImprimir()) {

        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();
        response.setContentType("application/x-pdf");
        response.setHeader("Content-Disposition", "attachment; filename=\"etiquetas.pdf\"");

        // step 1
        Document document = new Document(new Rectangle(86, 35));
        // step 2

        document.setMargins(0f, 0f, 0f, 0f);

        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
        // step 3
        document.open();/*from  ww  w  . j  av  a  2  s . com*/

        // step 4
        PdfContentByte cb = writer.getDirectContent();

        for (ProductoCantidad p : productos) {
            if (p.getCantidad() > 0) {

                BarcodeEAN codeEAN = new BarcodeEAN();
                codeEAN.setCode(p.getCodigo());
                codeEAN.setCodeType(Barcode.EAN13);
                codeEAN.setBarHeight(10f);
                codeEAN.setX(0.7f);
                codeEAN.setSize(4f);

                NumberFormat nf = NumberFormat.getCurrencyInstance(new Locale("es", "py"));
                Font fontbold = FontFactory.getFont("Times-Roman", 5, Font.NORMAL);
                Chunk productTitle = new Chunk(p.getNombre() + "," + " " + nf.format(p.getPrecio()), fontbold);

                // EAN 13
                Paragraph pTitile = new Paragraph(productTitle);
                pTitile.setAlignment(Element.ALIGN_CENTER);
                pTitile.setLeading(0, 1);

                PdfPTable table = new PdfPTable(1);
                table.setPaddingTop(0f);

                table.setWidthPercentage(96);
                PdfPCell cell = new PdfPCell();
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setBorder(Rectangle.NO_BORDER);
                cell.addElement(codeEAN.createImageWithBarcode(cb, null, BaseColor.BLACK));

                table.addCell(cell);

                PdfPCell cell2 = new PdfPCell();
                cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell2.setBorder(Rectangle.NO_BORDER);
                cell2.addElement(pTitile);

                table.addCell(cell2);

                for (int i = 0; i < p.getCantidad(); i++) {
                    document.add(table);
                    document.newPage();
                }
            }
        }

        // step 5
        document.close();

        response.getOutputStream().flush();
        response.getOutputStream().close();
        FacesContext.getCurrentInstance().responseComplete();
    } else {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "No hay nada que imprimir", ""));
    }
    return null;
}