Example usage for org.apache.pdfbox.pdmodel PDPage PDPage

List of usage examples for org.apache.pdfbox.pdmodel PDPage PDPage

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDPage PDPage.

Prototype

public PDPage() 

Source Link

Document

Creates a new PDPage instance for embedding, with a size of U.S.

Usage

From source file:de.schneefisch.fruas.transactions.DeliveryNotePDFCreator.java

public void createPDF() {

    String filename = "Lieferschein-" + deliveryNote.getId() + ".pdf";

    try {//from  w  w  w.  j  a  v a2s  . co m
        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);

        PDPageContentStream content = new PDPageContentStream(doc, page);

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 14);
        content.newLineAtOffset(70, 750);
        content.showText("Schneefisch GmbH");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 13);
        content.newLineAtOffset(70, 725);
        content.showText("Nibelungenplatz 1");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 14);
        content.newLineAtOffset(70, 700);
        content.showText("D-60318 Frankfurt am Main");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, 640);
        content.showText(fiCustomer.getName());
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, 620);
        content.showText("Wareneingang");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, 600);
        content.showText(location.getStreet() + " " + location.getHouseNumber());
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, 580);
        content.showText(location.getPostalCode() + " " + location.getCity());
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(300, 540);
        content.showText("Lieferschein " + deliveryNote.getId() + " fuer KN " + fiCustomer.getId());
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(75, 500);
        content.showText("POS");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(120, 500);
        content.showText("Bezeichnung");
        content.endText();

        int count = 1;
        float yoffset = 460;
        for (DeliveryNotePosition dnp : deliveryNotePositions) {
            LicenseDAO licDAO = new LicenseDAO();
            License license = licDAO.selectLicenseById(dnp.getLicenseId());
            ProductDAO pDAO = new ProductDAO();
            Product product = pDAO.searchProductById(license.getProductId());

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 12);
            content.newLineAtOffset(75, yoffset);
            content.showText(Integer.toString(count));
            content.endText();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 12);
            content.newLineAtOffset(120, yoffset);
            content.showText(product.getName());
            content.endText();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 12);
            content.newLineAtOffset(120, yoffset - 20);
            content.showText("Lizenz: " + license.getId() + " von " + license.getSoldDate() + " bis "
                    + license.getEndDate() + ".");
            content.endText();
            if (license.getMaintenanceId() == 0) {
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, 12);
                content.newLineAtOffset(120, yoffset - 40);
                content.showText("Ohne Maintenance-Vertrag.");
                content.endText();
            } else {
                MaintenanceDAO mDAO = new MaintenanceDAO();
                Maintenance maintenance = mDAO.searchMaintenanceById(license.getMaintenanceId());
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, 12);
                content.newLineAtOffset(120, yoffset - 40);
                content.showText("Mit " + maintenance.getInfo() + " als Maintenance-Vertrag.");
                content.endText();
            }
            count++;
            yoffset -= 100;
        }

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, yoffset);
        content.showText("Rechnungslegung erfolgt separat.");
        content.endText();
        yoffset -= 20;

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, yoffset);
        content.showText("Das Produkt bleibt bis zur vollstndigen Bezahlung unser Eigentum.");
        content.endText();
        yoffset -= 20;

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, yoffset);
        content.showText("Mit freundlichen Gruessen");
        content.endText();
        yoffset -= 20;

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, yoffset);
        content.showText("Schneefisch GmbH");
        content.endText();
        content.close();

        doc.save(filename);
        doc.close();
        System.out.println(filename + " erstellt in: " + System.getProperty("user.dir"));
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

From source file:de.thb.ue.backend.util.PDFGeneration.java

License:Apache License

public static void createQRCPDF(List<BufferedImage> tickets, String evaluationUID, String subject,
        SemesterType semesterType, int year, File workingDirectory) {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    //        PDRectangle rectangle = new PDRectangle(page.findCropBox().getWidth(), 500);
    //        page.setCropBox(rectangle);

    document.addPage(page);/*from  w w w . j  a  v a2  s  .  c o  m*/
    PDXObjectImage pdImage;

    try {
        PDPageContentStream contentStream = new PDPageContentStream(document, page);

        int x = 0;
        // start from top of page instead of bottom
        // somehow the first row gets swallowed -> start with second row instead
        int y = (int) page.findCropBox().getHeight() - (new PDJpeg(document, tickets.get(0))).getHeight();

        int imageHeight;
        int imageWidth;
        String qrCodePurpose = "Evaluation QR-Codes fr das Fach " + subject + " im "
                + (semesterType == SemesterType.WINTER ? "Winter" : "Sommer") + "semester "
                + Integer.toString(year);
        PDFont font = PDType1Font.HELVETICA;
        int fontSize = 13;

        // center text horizontally
        float textWidth = font.getStringWidth(qrCodePurpose) / 1000 * fontSize;
        int textX = (int) ((page.findCropBox().getWidth() / 2) - (textWidth / 2));

        // add QR-Codes
        for (int i = 0; i < tickets.size(); i++) {

            pdImage = new PDJpeg(document, tickets.get(i));
            imageHeight = pdImage.getHeight();
            imageWidth = pdImage.getWidth();

            if ((imageWidth + x) > page.findCropBox().getWidth()) {
                x = 0;
                y -= imageHeight;
            }

            if (y <= 0) {
                writeText(contentStream, page, qrCodePurpose, imageHeight, textX,
                        (y + imageHeight) - (imageHeight / 4), fontSize, font);
                page = new PDPage();
                document.addPage(page);
                contentStream.close();
                contentStream = new PDPageContentStream(document, page);
                y = (int) page.findCropBox().getHeight() - pdImage.getHeight();
                x = 0;
            }

            contentStream.drawImage(pdImage, x, y);

            if (i + 1 >= tickets.size()) {
                writeText(contentStream, page, qrCodePurpose, imageHeight, textX, y - 20, fontSize, font);
            }
            x += imageWidth;
        }

        /*PDDocumentCatalog catalog = document.getDocumentCatalog();
        catalog.getAcroForm().setXFA(null);*/

        contentStream.close();
        if (!workingDirectory.exists()) {
            workingDirectory.mkdir();
        }
        File outputFile = new File(workingDirectory, "qrcodes.pdf");
        document.save(outputFile);

    } catch (IOException | COSVisitorException e) {
        e.printStackTrace();
    } finally {
        try {
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:domain.mediator.PDFGeneration.java

public static void printTodayPDF(List<Logbook> logbookList, Driver driver, Load load,
        GPSLocation currentLocation) throws IOException {

    Table logbookTable = LogbookList.drawLogbookTable(logbookList);

    File saveFile = new File("todayTable.pdf");
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);/*from  w ww  .j  a v  a  2 s  .co  m*/
    PDPageContentStream pageContentStream = new PDPageContentStream(document, page);

    float contentPositionX = 40;
    float contentPositionY = page.getMediaBox().getHeight() - 50;

    PDFGeneration.printHeaderAndDataTable(pageContentStream, contentPositionX, contentPositionY, driver, load,
            currentLocation, logbookTable);

    pageContentStream.close();

    document.save(saveFile);
    document.close();
    PDFGeneration.openFile(saveFile);
}

From source file:domain.mediator.PDFGeneration.java

public static void printRecapPDF(List<Recap> recapList, Driver driver, Load load, GPSLocation currentLocation)
        throws IOException {

    Table recapTable = RecapList.drawRecapTable(recapList);

    File saveFile = new File("recapTable.pdf");
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);//w  w w. j a  v  a  2s  .  c  om
    PDPageContentStream pageContentStream = new PDPageContentStream(document, page);

    float contentPositionX = 40;
    float contentPositionY = page.getMediaBox().getHeight() - 50;

    PDFGeneration.printHeaderAndDataTable(pageContentStream, contentPositionX, contentPositionY, driver, load,
            currentLocation, recapTable);

    pageContentStream.close();

    document.save(saveFile);
    document.close();
    PDFGeneration.openFile(saveFile);
}

From source file:dtlgenerator.myDataReader.java

public void PdfGenerator(String pdfFileNameBase, List<String> cycles) throws IOException, COSVisitorException {
    GlobalVar.dirMake(new File(pdfFileNameBase)); //create a folder with the same name

    int rowCount = 0;
    int pageCount = 1;
    PDPage page; //default size PAGE_SIZE_A4
    PDPageContentStream stream;/*from w w  w  .  j a  v a2 s . c om*/
    //page.setRotation(90); //counterclock wise rotate 90 degree  ////left hand rule

    //        stream.setFont(PDType1Font.COURIER, FONT_SIZE);
    String lastUpdate = null;
    String lastCycle = null;
    System.out.println("DTL_DATA keyset:" + DTL_DATA.keySet());
    System.out.println("Cycles empty? " + cycles.isEmpty());
    System.out.println(cycles);
    for (String updateDate : DTL_DATA.keySet()) {
        Map<String, List<String>> thisDTData = DTL_DATA.get(updateDate);
        lastUpdate = updateDate;
        System.out.println("thisDT_DATA keyset:" + thisDTData.keySet());
        for (String cycle : thisDTData.keySet()) {
            if (cycles.isEmpty() || cycles.contains(cycle)) {
                PDDocument pdf = new PDDocument();
                lastCycle = cycle;
                List<String> thisCycle = thisDTData.get(cycle);
                pageCount = 1; // new cycle, restart page num
                page = new PDPage(); //page break
                stream = new PDPageContentStream(pdf, page, true, false);
                stream.beginText();
                page.setRotation(PAGE_ROT_DEGREE);
                //stream.setFont(PDType1Font.COURIER, FONT_SIZE);
                addBigFontUpdateNumberAndCycle(updateDate, cycle, stream);
                stream.setFont(PDType1Font.COURIER, FONT_SIZE);
                // stream.setFont(PDType1Font.
                int thisCycleRowCount = 0;
                for (String row : thisCycle) {
                    if (thisCycleRowCount > MAX_NUM_TRANS) {
                        //close the current page
                        setupFootNote(stream, pageCount, cycle, updateDate);
                        pageCount++;
                        stream.endText();
                        stream.close();
                        pdf.addPage(page);

                        // start a new page
                        page = new PDPage();
                        stream = new PDPageContentStream(pdf, page, true, false);
                        page.setRotation(PAGE_ROT_DEGREE);
                        stream.beginText();
                        stream.setFont(PDType1Font.COURIER, FONT_SIZE);
                        thisCycleRowCount = 0;
                    }
                    stream.setTextRotation(TEXT_ROT_RAD, TRANS_X + thisCycleRowCount * INVERVAL_X, TRANS_Y);
                    stream.drawString(row);
                    thisCycleRowCount++;
                    //System.out.println("Update:" + updateDate + " Cycle: " + cycle + " " + row);
                }
                setupFootNote(stream, pageCount, lastCycle, lastUpdate);
                stream.endText();
                stream.close();
                pdf.addPage(page);
                String pdfFileName = pdfFileNameBase + "\\DTL UPDT " + updateDate + " " + cycle + ".pdf";

                pdf.save(pdfFileName);
                pdf.close();
            }
        }
    }

    // pdf.save(pdfFileName);        
    // pdf.close();      
}

From source file:elaborate.editor.export.pdf.PdfMaker.java

License:Open Source License

public PdfMaker(Project _project, EntityManager _entityManager) {
    this.project = _project;
    this.entityManager = _entityManager;
    if (_project == null) {
        doc = null;//from  ww w .ja  v  a2 s . c o  m

    } else {
        try {
            doc = new PDDocument();

            ProjectService projectService = ProjectService.instance();
            projectService.setEntityManager(entityManager);
            List<ProjectEntry> projectEntriesInOrder = projectService.getProjectEntriesInOrder(project.getId());

            for (ProjectEntry projectEntry : projectEntriesInOrder) {
                PDPage page = new PDPage();
                doc.addPage(page);

                PDFont font = PDType1Font.HELVETICA_BOLD;

                PDPageContentStream content = new PDPageContentStream(doc, page);
                content.beginText();
                content.setFont(font, 12);
                content.drawString(projectEntry.getName());
                for (Transcription transcription : projectEntry.getTranscriptions()) {
                    content.drawString(transcription.getTextLayer());
                    content.drawString(transcription.getBody());
                }

                content.endText();
                content.close();
            }

        } catch (Exception e) {
            System.out.println("Exception");
        }
    }
}

From source file:es.rickyepoderi.pdfimages.Converter.java

License:Open Source License

/**
 * Method that converts the images provides to pdf and writes to the target 
 * path specified.//from  ww w  .j a v  a  2  s.  c  o m
 *
 * @param output The file to write
 * @param bimages The buffered images to put in the pdf
 * @throws IOException Some error generating the PDF
 */
public void images2Pdf(File output, File... files) throws IOException {
    try (PDDocument pdDocument = new PDDocument()) {
        for (File file : files) {
            PDPage page = new PDPage();
            pdDocument.addPage(page);
            try (PDPageContentStream pageStream = new PDPageContentStream(pdDocument, page,
                    PDPageContentStream.AppendMode.APPEND, true, true)) {
                BufferedImage bimage = ImageIO.read(file);
                PDImageXObject img = LosslessFactory.createFromImage(pdDocument, bimage);
                Dimension scaledDim = getScaledDimension(new Dimension(img.getWidth(), img.getHeight()),
                        new Dimension((int) page.getMediaBox().getWidth(),
                                (int) page.getMediaBox().getHeight()));
                pageStream.drawImage(img, 0, 0, scaledDim.width, scaledDim.height);
            }
        }
        pdDocument.save(output);
    }
}

From source file:es.udc.fic.medregatas.util.PDFUtils.java

public static void printPDF(String docName) throws IOException, COSVisitorException {

    createPdfDirectoryIfNotExists();//from  w  w w . j a va2 s  .  c  o m

    // Create a document and add a page to it
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);

    // Create a new font object selecting one of the PDF base fonts
    PDFont font = PDType1Font.HELVETICA_BOLD;

    // Start a new content stream which will "hold" the to be created content
    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    // Define a text content stream using the selected font, moving the 
    // cursor and drawing the text "Hello World"
    contentStream.beginText();

    contentStream.setFont(font, 12);
    contentStream.moveTextPositionByAmount(100, 700);
    contentStream.drawString("Hello World");
    contentStream.endText();

    // Make sure that the content stream is closed:
    contentStream.close();

    // Save the results and ensure that the document is properly closed:
    document.save(PDFS_FOLDER + "/" + docName);
    document.close();
}

From source file:fi.nls.oskari.printout.printing.pdfbox.UsingTextMatrix.java

License:Apache License

/**
 * creates a sample document with some text using a text matrix.
 * //ww  w . jav a2 s .  c o m
 * @param message
 *            The message to write in the file.
 * @param outfile
 *            The resulting PDF.
 * 
 * @throws IOException
 *             If there is an error writing the data.
 * @throws COSVisitorException
 *             If there is an error writing the PDF.
 */
public void doIt(String message, String outfile) throws IOException, COSVisitorException {
    // the document
    PDDocument doc = null;
    try {
        doc = new PDDocument();

        // Page 1
        PDFont font = PDType1Font.HELVETICA;
        PDPage page = new PDPage();
        page.setMediaBox(PDPage.PAGE_SIZE_A4);
        doc.addPage(page);
        float fontSize = 12.0f;

        PDRectangle pageSize = page.findMediaBox();

        System.err.println("pageSize " + pageSize);
        System.err.println(
                "pageSize cm " + pageSize.getWidth() / 72 * 2.54 + "," + pageSize.getHeight() / 72 * 2.54);

        float centeredXPosition = (pageSize.getWidth() - fontSize / 1000f) / 2f;
        float stringWidth = font.getStringWidth(message);
        float centeredYPosition = (pageSize.getHeight() - (stringWidth * fontSize) / 1000f) / 3f;

        PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, false);
        contentStream.setFont(font, fontSize);
        contentStream.beginText();
        // counterclockwise rotation
        for (int i = 0; i < 8; i++) {
            contentStream.setTextRotation(i * Math.PI * 0.25, centeredXPosition,
                    pageSize.getHeight() - centeredYPosition);
            contentStream.drawString(message + " " + i);
        }
        // clockwise rotation
        for (int i = 0; i < 8; i++) {
            contentStream.setTextRotation(-i * Math.PI * 0.25, centeredXPosition, centeredYPosition);
            contentStream.drawString(message + " " + i);
        }

        contentStream.endText();
        contentStream.close();

        // Page 2
        page = new PDPage();
        page.setMediaBox(PDPage.PAGE_SIZE_A4);
        doc.addPage(page);
        fontSize = 1.0f;

        contentStream = new PDPageContentStream(doc, page, false, false);
        contentStream.setFont(font, fontSize);
        contentStream.beginText();

        // text scaling
        for (int i = 0; i < 10; i++) {
            contentStream.setTextScaling(12 + (i * 6), 12 + (i * 6), 100, 100 + i * 50);
            contentStream.drawString(message + " " + i);
        }
        contentStream.endText();
        contentStream.close();

        // Page 3
        page = new PDPage();
        page.setMediaBox(PDPage.PAGE_SIZE_A4);
        doc.addPage(page);
        fontSize = 1.0f;

        contentStream = new PDPageContentStream(doc, page, false, false);
        contentStream.setFont(font, fontSize);
        contentStream.beginText();

        int i = 0;
        // text scaling combined with rotation
        contentStream.setTextMatrix(12, 0, 0, 12, centeredXPosition, centeredYPosition * 1.5);
        contentStream.drawString(message + " " + i++);

        contentStream.setTextMatrix(0, 18, -18, 0, centeredXPosition, centeredYPosition * 1.5);
        contentStream.drawString(message + " " + i++);

        contentStream.setTextMatrix(-24, 0, 0, -24, centeredXPosition, centeredYPosition * 1.5);
        contentStream.drawString(message + " " + i++);

        contentStream.setTextMatrix(0, -30, 30, 0, centeredXPosition, centeredYPosition * 1.5);
        contentStream.drawString(message + " " + i++);

        contentStream.endText();
        contentStream.close();

        // Page 4
        {
            page = new PDPage();
            page.setMediaBox(PDPage.PAGE_SIZE_A4);
            doc.addPage(page);
            fontSize = 1.0f;

            contentStream = new PDPageContentStream(doc, page, false, false);
            contentStream.setFont(font, fontSize);
            contentStream.beginText();

            AffineTransform root = new AffineTransform();
            root.scale(72.0 / 2.54, 72.0 / 2.54);

            for (i = 0; i < pageSize.getHeight() / 72 * 2.54; i++) {
                // text scaling combined with rotation
                {
                    AffineTransform rowMatrix = new AffineTransform(root);
                    rowMatrix.translate(1, i);
                    contentStream.setTextMatrix(rowMatrix);
                    contentStream.drawString(message + " " + i);
                }

            }

            contentStream.endText();
            contentStream.close();
        }

        doc.save(outfile);
    } finally {
        if (doc != null) {
            doc.close();
        }
    }
}

From source file:generarPDF.GenerarFactura.java

public PDDocument crearFactura(int facturaID, JFrame dialogo) {

    try {/*  www . j  a v  a  2  s .c  o  m*/

        ControladorFactura controladorFactura = new ControladorFactura();
        Factura facturaActual = controladorFactura.getFactura(" where factura_id=" + facturaID).get(0);

        ControladorCliente controladorCliente = new ControladorCliente();
        Cliente cliente = controladorCliente.obtenerClientePorID(facturaActual.getCliente_id());

        System.out.println(cliente.getCliente_id());

        PDDocument document = new PDDocument();

        PDPage pagina1 = new PDPage();
        document.addPage(pagina1);

        PDFont font = PDType1Font.HELVETICA_BOLD;
        PDFont fontNormal = PDType1Font.HELVETICA;

        PDPageContentStream contenido = new PDPageContentStream(document, pagina1);

        contenido.beginText();
        contenido.setFont(font, 16);
        contenido.moveTextPositionByAmount(30, 730);
        System.out.println("llego aqui -10");

        contenido.drawString("Factura #" + facturaActual.getFactura_id());
        contenido.endText();
        System.out.println("llego aqui -11");

        contenido.beginText();
        contenido.setFont(font, 12);
        contenido.moveTextPositionByAmount(30, 700);
        contenido.drawString(nombreEmpresa + " NIT: " + NITEmpresa);
        contenido.endText();

        contenido.beginText();
        contenido.setFont(font, 12);
        contenido.moveTextPositionByAmount(30, 680);
        contenido.drawString(direccionEmpresa);
        contenido.endText();

        contenido.beginText();
        contenido.setFont(fontNormal, 11);
        contenido.moveTextPositionByAmount(30, 650);
        contenido.drawString("Fecha:" + facturaActual.getFecha());
        contenido.endText();

        contenido.beginText();
        contenido.setFont(fontNormal, 11);
        contenido.moveTextPositionByAmount(30, 635);
        contenido.drawString("Nombre: " + cliente.getNombre());
        contenido.endText();

        contenido.beginText();
        contenido.setFont(fontNormal, 11);
        contenido.moveTextPositionByAmount(30, 620);
        contenido.drawString("Direccin: " + cliente.getDireccion());
        contenido.endText();

        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(200, 590);
        contenido.drawString("DETALLE DE LA FACTURA");
        contenido.endText();

        //Dibujar lineas
        contenido.drawLine(30, 600, 500, 600);
        contenido.drawLine(30, 585, 500, 585);

        //Dibujar tabla de productos
        ControladorFactura_Productos controladorFactura_Productos = new ControladorFactura_Productos();
        ArrayList<Factura_Productos> listaProductosFactura = controladorFactura_Productos
                .getTodosFactura_Productos(" where factura_id=" + facturaID);

        contenido.drawLine(30, 570, 500, 570);

        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(60, 560);
        contenido.drawString("Producto");
        contenido.endText();
        contenido.drawLine(30, 550, 30, 570);
        contenido.drawLine(200, 550, 200, 570);

        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(220, 560);
        contenido.drawString("Valor unitario");
        contenido.endText();
        contenido.drawLine(300, 550, 300, 570);

        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(320, 560);
        contenido.drawString("Unidades");
        contenido.endText();
        contenido.drawLine(380, 550, 380, 570);

        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(400, 560);
        contenido.drawString("Valor total");
        contenido.endText();
        contenido.drawLine(500, 550, 500, 570);
        contenido.drawLine(500, 550, 500, 570);

        contenido.drawLine(30, 550, 500, 550);

        int altura = 550;
        ControladorProducto controladorProducto = new ControladorProducto();

        /*
         * Caben en la pagina
         * Primera pagina 14
         * Seguientes paginas 21
         * Footer cuenta como 5 mas
         */
        int indiceProductos = 0;
        double totalEspaciosNecesarios = listaProductosFactura.size() + 5 + 1;
        double totalPaginas = 1;

        if (Math.floor(totalEspaciosNecesarios / 17) == 0) {
            totalPaginas = 1;
        } else {
            totalEspaciosNecesarios -= 17;
            totalPaginas += (int) Math.ceil(totalEspaciosNecesarios / 21);
        }

        //Primer pagina
        for (int i = 0; i < listaProductosFactura.size() && altura >= 30; i++) {
            //Imprime por paginas
            Factura_Productos facturaProducto = listaProductosFactura.get(i);
            Productos productoActual = controladorProducto
                    .getProducto(" where producto_id=" + facturaProducto.getProducto_id()).get(0);

            String nombreProducto = productoActual.getNombre();

            if (nombreProducto.length() > 25) {
                nombreProducto = nombreProducto.substring(0, 26);
            }

            Double totalProducto = productoActual.getPrecio() * facturaProducto.getUnidades();
            NumberFormat formatter = new DecimalFormat("#0");

            String valorUnitario = String.valueOf(productoActual.getPrecio());
            String unidades = String.valueOf(facturaProducto.getUnidades());
            String valorTotal = String.valueOf(formatter.format(totalProducto));

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(40, altura - 15);
            contenido.drawString(String.valueOf(i + 1));
            contenido.endText();
            contenido.drawLine(30, altura, 30, altura - 30);
            contenido.drawLine(200, altura, 200, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(70, altura - 15);
            contenido.drawString(nombreProducto);
            contenido.endText();
            contenido.drawLine(70, altura, 70, altura - 30);
            contenido.drawLine(200, altura, 200, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(220, altura - 15);
            contenido.drawString(valorUnitario);
            contenido.endText();
            contenido.drawLine(300, altura, 300, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(320, altura - 15);
            contenido.drawString(unidades);
            contenido.endText();
            contenido.drawLine(380, altura, 380, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(400, altura - 15);
            contenido.drawString(valorTotal);
            contenido.endText();
            contenido.drawLine(500, altura, 500, altura - 30);
            //Linea inferior
            contenido.drawLine(30, altura - 30, 500, altura - 30);
            altura -= 30;
            indiceProductos = i + 1;
        }
        //Escribir footer si paginas es igual a 1
        if (totalPaginas == 1) {
            Double valor = facturaActual.getValor();
            Double ivaCalculado = Math.ceil(valor * Double.parseDouble(IVA) / 100);
            Double subtotal = Math.floor(valor * (1 - Double.parseDouble(IVA) / 100));

            NumberFormat formatter = new DecimalFormat("#0");
            String valorFormateado = formatter.format(valor);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(320, altura - 15);
            contenido.drawString("Subtotal");
            contenido.endText();
            contenido.drawLine(380, altura, 380, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(400, altura - 15);
            contenido.drawString(String.valueOf(subtotal));
            contenido.endText();
            contenido.drawLine(500, altura, 500, altura - 30);

            //Linea inferior
            contenido.drawLine(320, altura, 320, altura - 30);
            contenido.drawLine(320, altura - 30, 500, altura - 30);

            altura -= 30;
            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(320, altura - 15);
            contenido.drawString("IVA " + IVA + "%");
            contenido.endText();
            contenido.drawLine(380, altura, 380, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(400, altura - 15);
            contenido.drawString(String.valueOf(ivaCalculado));
            contenido.endText();
            contenido.drawLine(500, altura, 500, altura - 30);
            //Linea inferior
            contenido.drawLine(320, altura, 320, altura - 30);
            contenido.drawLine(320, altura - 30, 500, altura - 30);
            altura -= 30;

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(320, altura - 15);
            contenido.drawString("Total");
            contenido.endText();
            contenido.drawLine(380, altura, 380, altura - 30);

            contenido.beginText();
            contenido.setFont(font, 12);
            contenido.moveTextPositionByAmount(400, altura - 15);
            contenido.drawString(valorFormateado);
            contenido.endText();
            contenido.drawLine(500, altura, 500, altura - 30);
            //Linea inferior
            contenido.drawLine(320, altura - 30, 500, altura - 30);
            contenido.drawLine(320, altura, 320, altura - 30);

            //Informacion legal
            altura -= 40;
            contenido.beginText();
            contenido.setFont(fontNormal, 10);
            contenido.moveTextPositionByAmount(50, altura);
            contenido.drawString(informacionLegalFactura);
            contenido.endText();

        }

        //Siguientes paginas
        for (int j = 1; j < totalPaginas; j++) {
            altura = 650;
            PDPage paginaSiguiente = new PDPage();
            document.addPage(paginaSiguiente);

            PDPageContentStream contenidoSiguiente = new PDPageContentStream(document, paginaSiguiente);
            //Escribir paginas
            for (int i = indiceProductos; i < listaProductosFactura.size() && altura >= 30; i++) {
                //Imprime por paginas
                Factura_Productos facturaProducto = listaProductosFactura.get(i);
                Productos productoActual = controladorProducto
                        .getProducto(" where producto_id=" + facturaProducto.getProducto_id()).get(0);

                String nombreProducto = productoActual.getNombre();

                if (nombreProducto.length() > 25) {
                    nombreProducto = nombreProducto.substring(0, 26);
                }

                Double totalProducto = productoActual.getPrecio() * facturaProducto.getUnidades();
                NumberFormat formatter = new DecimalFormat("#0");

                String valorUnitario = String.valueOf(productoActual.getPrecio());
                String unidades = String.valueOf(facturaProducto.getUnidades());
                String valorTotal = String.valueOf(formatter.format(totalProducto));

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(40, altura - 15);
                contenidoSiguiente.drawString(String.valueOf(i + 1));
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(30, altura, 30, altura - 30);
                contenidoSiguiente.drawLine(200, altura, 200, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(70, altura - 15);
                contenidoSiguiente.drawString(nombreProducto);
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(70, altura, 70, altura - 30);
                contenidoSiguiente.drawLine(200, altura, 200, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(320, altura - 15);
                contenidoSiguiente.drawString(unidades);
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(380, altura, 380, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(font, 12);
                contenidoSiguiente.moveTextPositionByAmount(400, altura - 15);
                contenidoSiguiente.drawString(valorTotal);
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(500, altura, 500, altura - 30);
                //Linea inferior
                contenidoSiguiente.drawLine(30, altura - 30, 500, altura - 30);
                indiceProductos = i + 1;
                altura -= 30;
            }
            //Si no cabe mas cierre el flujo.
            if (indiceProductos < listaProductosFactura.size()) {
                contenidoSiguiente.close();
            }
            //En ultima pagina escribir footer
            if (j == totalPaginas - 1 && altura >= 40) {
                Double valor = facturaActual.getValor();
                Double ivaCalculado = Math.ceil(valor * Double.parseDouble(IVA) / 100);
                Double subtotal = Math.floor(valor * (1 - Double.parseDouble(IVA) / 100));
                NumberFormat formatter = new DecimalFormat("#0");
                String valorFormateado = formatter.format(valor);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(320, altura - 15);
                contenidoSiguiente.drawString("Subtotal");
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(380, altura, 380, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(400, altura - 15);
                contenidoSiguiente.drawString(String.valueOf(subtotal));
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(500, altura, 500, altura - 30);

                //Linea inferior
                contenidoSiguiente.drawLine(320, altura, 320, altura - 30);
                contenidoSiguiente.drawLine(320, altura - 30, 500, altura - 30);

                altura -= 30;
                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(320, altura - 15);
                contenidoSiguiente.drawString("IVA " + IVA + "%");
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(380, altura, 380, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(400, altura - 15);
                contenidoSiguiente.drawString(String.valueOf(ivaCalculado));
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(500, altura, 500, altura - 30);
                //Linea inferior
                contenidoSiguiente.drawLine(320, altura, 320, altura - 30);
                contenidoSiguiente.drawLine(320, altura - 30, 500, altura - 30);
                altura -= 30;

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(320, altura - 15);
                contenidoSiguiente.drawString("Total");
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(380, altura, 380, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(400, altura - 15);
                contenidoSiguiente.drawString(valorFormateado);
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(500, altura, 500, altura - 30);
                //Linea inferior
                contenidoSiguiente.drawLine(320, altura - 30, 500, altura - 30);
                contenidoSiguiente.drawLine(320, altura, 320, altura - 30);

                //Informacion legal
                altura -= 40;
                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 10);
                contenidoSiguiente.moveTextPositionByAmount(50, altura);
                contenidoSiguiente.drawString(informacionLegalFactura);
                contenidoSiguiente.endText();

                contenidoSiguiente.close();
            } else {
                contenidoSiguiente.close();
            }

            System.out.println("Pagina numero: " + j + " De  " + totalPaginas);

        }

        contenido.close();
        return document;

    } catch (Exception e) {
        JOptionPane.showMessageDialog(dialogo,
                "Error al crear la factura\nInformacin Tcnica\n" + e.toString(), "Error",
                JOptionPane.ERROR_MESSAGE);
        return null;
    }

}