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(COSDictionary pageDictionary) 

Source Link

Document

Creates a new instance of PDPage for reading.

Usage

From source file:correccioncolorpdfs.CorrectorColorUI.java

private void transformarPDF() {
    try {/*  w  w  w. j a v a 2  s .  c  o  m*/
        //@see http://stackoverflow.com/questions/18189314/convert-a-pdf-file-to-image
        String rutaPDFOriginal = rutaPDF + nombrePDF; // Pdf files are read from this folder
        //String destinationDir = "D:\\Desarrollo\\pruebas\\reportes_negros\\imagenes\\"; // converted images from pdf document are saved here

        File pdfOriginal = new File(rutaPDFOriginal);
        //            File destinationFile = new File(destinationDir);
        //            if (!destinationFile.exists()) {
        //                destinationFile.mkdir();
        //                System.out.println("Folder Created -> " + destinationFile.getAbsolutePath());
        //            }
        if (pdfOriginal.exists()) {
            //System.out.println("Images copied to Folder: " + destinationFile.getName());
            PDDocument document = PDDocument.load(rutaPDFOriginal);

            //Documento Fondo Blanco
            PDDocument documentoCool = new PDDocument();

            List<PDPage> list = document.getDocumentCatalog().getAllPages();
            System.out.println("Total files to be converted -> " + list.size());

            String nombrePDFOriginal = pdfOriginal.getName().replace(".pdf", "");
            int pageNumber = 1;
            for (PDPage page : list) {
                BufferedImage image = page.convertToImage();

                //Inviertiendo colores
                //@see http://stackoverflow.com/questions/8662349/convert-negative-image-to-positive
                for (int x = 0; x < image.getWidth(); x++) {
                    for (int y = 0; y < image.getHeight(); y++) {
                        int rgba = image.getRGB(x, y);
                        //Hexa a reemplazar e9e9e1 R=233|G=233|B=225
                        Color col = new Color(rgba, true);
                        col = new Color(255 - col.getRed(), 255 - col.getGreen(), 255 - col.getBlue());

                        //Si color es igual al invertido - cambiarlo a blanco
                        if (col.getRGB() == -1447455) {
                            col = new Color(255, 255, 255);
                        }
                        //System.out.println("col.getR = " + col.getRGB());
                        image.setRGB(x, y, col.getRGB());
                    }
                }
                //                    File outputfile = new File(destinationDir + fileName + "_" + pageNumber + ".png");
                //                    System.out.println("Image Created -> " + outputfile.getName());
                //                    ImageIO.write(image, "png", outputfile);
                pageNumber++;

                //Crear pagina nueva para el PDF Convertido
                float width = image.getWidth();
                float height = image.getHeight();
                PDPage paginaSinFondo = new PDPage(new PDRectangle(width, height));
                documentoCool.addPage(paginaSinFondo);
                PDXObjectImage img = new PDJpeg(documentoCool, image);
                PDPageContentStream contentStream = new PDPageContentStream(documentoCool, paginaSinFondo);
                contentStream.drawImage(img, 0, 0);
                contentStream.close();

            }
            document.close();
            rutaPDFImprimible = rutaPDF + nombrePDFOriginal + "_imprimible.pdf";
            documentoCool.save(rutaPDFImprimible);
            documentoCool.close();

            estadoConversion(true);
        } else {
            JOptionPane.showMessageDialog(this,
                    "No se logr identificar la ruta del archivo, por favor verifique que el archivo si existe o no halla sido movido durante el proceso.",
                    "Ruta de archivo no encontrada", JOptionPane.WARNING_MESSAGE);
        }

    } catch (IOException | COSVisitorException | HeadlessException e) {
        estadoConversion(false);
        JOptionPane.showMessageDialog(this, e.getMessage(), "Error durante el proceso de conversin",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:costumetrade.common.util.PdfUtils.java

License:Open Source License

public static PDDocument createImagePdf(File file) {

    PDPageContentStream contentStream = null;
    try {// w  w  w.java 2  s  .co  m
        BufferedImage bimg = ImageIO.read(file);
        PDDocument document = new PDDocument();
        PDPage page = new PDPage(new PDRectangle(bimg.getWidth(), bimg.getHeight()));
        document.addPage(page);
        PDImageXObject image = PDImageXObject.createFromFileByExtension(file, document);
        contentStream = new PDPageContentStream(document, page);
        contentStream.drawImage(image, 0, 0);
        return document;
    } catch (IOException e) {
        throw new RuntimeException("?PDF", e);
    } finally {
        IOUtils.closeQuietly(contentStream);
    }

}

From source file:de.hrogge.CompactPDFExport.PDFSeite.java

License:Apache License

protected void neueSeite() {
    this.page = new PDPage(PDPage.PAGE_SIZE_A4);
    this.doc.addPage(page);
}

From source file:de.katho.kBorrow.controller.NewLendingController.java

License:Open Source License

/**
 * Erzeugt ein PDF-File mit allen relevanten Daten zur als Parameter bergebenen Lending-ID.
 * //from  w w  w  .j a  v a 2s .c  o  m
 * @param pLendingId   ID der Ausleihe, fr die ein PDF erzeugt werden soll.
 * @throws Exception   Wenn Probleme beim Erstellen der Datei auftreten.
 */
private void createPdfFile(int pLendingId) throws Exception {
    KLending lending = kLendingModel.getElement(pLendingId);
    KArticle article = kArticleModel.getElement(lending.getArticleId());
    KUser user = kUserModel.getElement(lending.getUserId());
    KLender lender = kLenderModel.getElement(lending.getLenderId());

    PDDocument doc = new PDDocument();
    PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
    PDRectangle rect = page.getMediaBox();
    doc.addPage(page);

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

    String[] text = { "Artikel: ", "Verliehen von: ", "Ausgeliehen an: ", "Start der Ausleihe: ",
            "Voraussichtliche Rckgabe: " };
    String[] vars = { article.getName(), user.getName() + " " + user.getSurname(),
            lender.getName() + " " + lender.getSurname() + " (" + lender.getStudentnumber() + ")",
            lending.getStartDate(), lending.getExpectedEndDate() };
    try {
        File file = createRandomPdf();

        PDPageContentStream cos = new PDPageContentStream(doc, page);

        cos.beginText();
        cos.moveTextPositionByAmount(100, rect.getHeight() - 100);
        cos.setFont(fontBold, 16);
        cos.drawString("Ausleihe #" + lending.getId());
        cos.endText();

        int i = 0;

        while (i < text.length) {
            cos.beginText();
            cos.moveTextPositionByAmount(100, rect.getHeight() - 25 * (i + 2) - 100);
            cos.setFont(fontBold, 12);
            cos.drawString(text[i]);
            cos.moveTextPositionByAmount(rect.getWidth() / 2 - 100, 0);
            cos.setFont(fontNormal, 12);
            cos.drawString(vars[i]);
            cos.endText();
            i++;
        }

        i = i + 2;
        cos.setLineWidth(1);
        cos.addLine(100, rect.getHeight() - 25 * (i + 2) - 100, 300, rect.getHeight() - 25 * (i + 2) - 100);
        cos.closeAndStroke();

        i++;

        cos.beginText();
        cos.moveTextPositionByAmount(100, rect.getHeight() - 25 * (i + 2) - 100);
        cos.setFont(fontNormal, 12);
        cos.drawString("Unterschrift " + lender.getName() + " " + lender.getSurname());
        cos.endText();

        cos.close();
        doc.save(file);
        doc.close();

        if (Desktop.isDesktopSupported()) {
            Desktop desktop = Desktop.getDesktop();
            if (desktop.isSupported(Desktop.Action.OPEN)) {
                desktop.open(file);
            }
        }
    } catch (IOException | COSVisitorException e) {
        throw new Exception("Problem bei der Erstellung der PDF-Datei.", e);
    }
}

From source file:de.redsix.pdfcompare.CompareResult.java

License:Apache License

protected void addPageToDocument(final PDDocument document, final ImageWithDimension diffImage)
        throws IOException {
    PDPage page = new PDPage(new PDRectangle(diffImage.width, diffImage.height));
    document.addPage(page);//from ww  w.j av a 2  s  .co  m
    final PDImageXObject diffXImage = LosslessFactory.createFromImage(document, diffImage.bufferedImage);
    /*      final PDImageXObject actualXObject = LosslessFactory.createFromImage(document, actualImage.bufferedImage);
            final PDImageXObject expectedXObject = LosslessFactory.createFromImage(document, expectedImage.bufferedImage);
    */ try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
        int x = (int) page.getCropBox().getWidth();
        //System.out.println("X value "+x);
        int y = (int) page.getCropBox().getHeight();
        //System.out.println("Y value "+y);
        contentStream.drawImage(diffXImage, 0, 0, x, y);
        /*         contentStream.setLineWidth(0.5F); 
                     contentStream.moveTo(x, 2);
                    contentStream.lineTo(x, y);
                     contentStream.drawImage(expectedXObject, x+2, 0, x, y);
                 contentStream.moveTo(x+x, 2);
                   contentStream.lineTo(x+x, y+y);
                   contentStream.drawImage(expectedXObject, x+x+2, 0, x, y);
                    contentStream.stroke();*/
    }
}

From source file:de.redsix.pdfcompare.CompareResult.java

License:Apache License

protected void addPageToDocument(final PDDocument document, final ImageWithDimension actualImage,
        final ImageWithDimension expectedImage) throws IOException {
    PDPage page = new PDPage(new PDRectangle(actualImage.width, actualImage.height));
    document.addPage(page);/*from   ww w  .ja v  a2s .  c  o  m*/
    //final PDImageXObject diffXImage = LosslessFactory.createFromImage(document, diffImage.bufferedImage);
    final PDImageXObject actualXObject = LosslessFactory.createFromImage(document, actualImage.bufferedImage);
    final PDImageXObject expectedXObject = LosslessFactory.createFromImage(document,
            expectedImage.bufferedImage);
    try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
        int x = (int) page.getCropBox().getWidth() / 2;
        //System.out.println("X value "+x);
        int y = (int) page.getCropBox().getHeight();
        //System.out.println("Y value "+y);
        contentStream.drawImage(actualXObject, 0, 0, x, y);
        contentStream.setLineWidth(0.5F);
        contentStream.moveTo(x, 2);
        contentStream.lineTo(x, y);
        contentStream.drawImage(expectedXObject, x + 2, 0, x, y);
        /*contentStream.moveTo(x+x, 2);
        contentStream.lineTo(x+x, y+y);
        contentStream.drawImage(expectedXObject, x+x+2, 0, x, y);*/
        contentStream.stroke();
    }
}

From source file:de.redsix.pdfcompare.CompareResult.java

License:Apache License

protected void addPageToDocument(final PDDocument document, final ImageWithDimension diffImage,
        final ImageWithDimension actualImage, final ImageWithDimension expectedImage) throws IOException {
    PDPage page = new PDPage(new PDRectangle(diffImage.width, diffImage.height));
    document.addPage(page);/* w  w w  .  j a  va 2s. c  om*/
    final PDImageXObject diffXImage = LosslessFactory.createFromImage(document, diffImage.bufferedImage);
    final PDImageXObject actualXObject = LosslessFactory.createFromImage(document, actualImage.bufferedImage);
    final PDImageXObject expectedXObject = LosslessFactory.createFromImage(document,
            expectedImage.bufferedImage);
    try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
        int x = (int) page.getCropBox().getWidth() / 3;
        System.out.println("X value " + x);
        int y = (int) page.getCropBox().getHeight();
        System.out.println("Y value " + y);
        contentStream.drawImage(diffXImage, 0, 0, x, y);
        contentStream.setLineWidth(0.5F);
        contentStream.moveTo(x, 2);
        contentStream.lineTo(x, y);
        contentStream.drawImage(actualXObject, x + 2, 0, x, y);
        contentStream.moveTo(x + x, 2);
        contentStream.lineTo(x + x, y + y);
        contentStream.drawImage(expectedXObject, x + x + 2, 0, x, y);
        contentStream.stroke();
    }
}

From source file:de.rototor.pdfbox.graphics2d.PdfBoxGraphics2DTestBase.java

License:Apache License

@SuppressWarnings("SpellCheckingInspection")
void exportGraphic(String dir, String name, GraphicsExporter exporter) {
    try {/* w w  w.  j a v  a  2 s . co m*/
        PDDocument document = new PDDocument();

        PDFont pdArial = PDFontFactory.createDefaultFont();

        File parentDir = new File("target/test/" + dir);
        // noinspection ResultOfMethodCallIgnored
        parentDir.mkdirs();

        BufferedImage image = new BufferedImage(400, 400, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D imageGraphics = image.createGraphics();
        exporter.draw(imageGraphics);
        imageGraphics.dispose();
        ImageIO.write(image, "PNG", new File(parentDir, name + ".png"));

        for (Mode m : Mode.values()) {
            PDPage page = new PDPage(PDRectangle.A4);
            document.addPage(page);

            PDPageContentStream contentStream = new PDPageContentStream(document, page);
            PdfBoxGraphics2D pdfBoxGraphics2D = new PdfBoxGraphics2D(document, 400, 400);
            PdfBoxGraphics2DFontTextDrawer fontTextDrawer = null;
            contentStream.beginText();
            contentStream.setStrokingColor(0, 0, 0);
            contentStream.setNonStrokingColor(0, 0, 0);
            contentStream.setFont(PDType1Font.HELVETICA_BOLD, 15);
            contentStream.setTextMatrix(Matrix.getTranslateInstance(10, 800));
            contentStream.showText("Mode " + m);
            contentStream.endText();
            switch (m) {
            case FontTextIfPossible:
                fontTextDrawer = new PdfBoxGraphics2DFontTextDrawer();
                registerFots(fontTextDrawer);
                break;
            case DefaultFontText: {
                fontTextDrawer = new PdfBoxGraphics2DFontTextDrawerDefaultFonts();
                registerFots(fontTextDrawer);
                break;
            }
            case ForceFontText:
                fontTextDrawer = new PdfBoxGraphics2DFontTextForcedDrawer();
                registerFots(fontTextDrawer);
                fontTextDrawer.registerFont("Arial", pdArial);
                break;
            case DefaultVectorized:
            default:
                break;
            }

            if (fontTextDrawer != null) {
                pdfBoxGraphics2D.setFontTextDrawer(fontTextDrawer);
            }

            exporter.draw(pdfBoxGraphics2D);
            pdfBoxGraphics2D.dispose();

            PDFormXObject appearanceStream = pdfBoxGraphics2D.getXFormObject();
            Matrix matrix = new Matrix();
            matrix.translate(0, 20);
            contentStream.transform(matrix);
            contentStream.drawForm(appearanceStream);

            matrix.scale(1.5f, 1.5f);
            matrix.translate(0, 100);
            contentStream.transform(matrix);
            contentStream.drawForm(appearanceStream);
            contentStream.close();
        }

        document.save(new File(parentDir, name + ".pdf"));
        document.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:dpfmanager.shell.modules.report.util.PDFParams.java

License:Open Source License

public void init(PDRectangle pageType) throws IOException {
    document = new PDDocument();
    PDPage page = new PDPage(pageType);
    document.addPage(page);//from   w ww  .  j  a v a2 s .co m
    contentStream = new PDPageContentStream(document, page);
}

From source file:dpfmanager.shell.modules.report.util.PDFParams.java

License:Open Source License

/**
 * New page pd page content stream./*ww w  .  j  a v  a2 s  .  c  o m*/
 *
 * @param contentStream the content stream
 * @param document      the document
 * @return the pd page content stream
 * @throws Exception the exception
 */
PDPageContentStream newPage(PDPageContentStream contentStream, PDDocument document) throws Exception {
    contentStream.close();
    PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
    document.addPage(page);
    return new PDPageContentStream(document, page);
}