Example usage for org.apache.pdfbox.pdmodel PDDocument close

List of usage examples for org.apache.pdfbox.pdmodel PDDocument close

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

This will close the underlying COSDocument object.

Usage

From source file:com.fileOperations.EmailBodyToPDF.java

/**
 * Places the text of the email into the PDF
 *
 * @param eml EmailBodyPDF/*from w  w  w.j  a  va 2 s.  c  o  m*/
 */
private static void createEmailBody(EmailBodyPDF eml) {
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    //Fonts used
    PDFont bodyTitleFont = PDType1Font.TIMES_BOLD;
    PDFont bodyFont = PDType1Font.TIMES_ROMAN;

    //Font Sizes
    float emailHeaderFontSize = 7;
    float leadingEmailHeader = 1.5f * emailHeaderFontSize;
    float bodyFontSize = 12;
    float leadingBody = 1.5f * bodyFontSize;

    try {
        //Create Document, Page, Margins.
        doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);
        contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);
        PDRectangle mediabox = page.getMediaBox();
        float margin = 72;
        float width = mediabox.getWidth() - 2 * margin;
        float startX = mediabox.getLowerLeftX() + margin;
        float startY = mediabox.getUpperRightY() - margin;
        float textYlocation = margin;

        //Set Line Breaks
        List<String> sentDateContent = PDFBoxTools.setLineBreaks(eml.getSentDate(), width, emailHeaderFontSize,
                bodyFont);
        List<String> recievedDateContent = PDFBoxTools.setLineBreaks(eml.getReceiveDate(), width,
                emailHeaderFontSize, bodyFont);
        List<String> toContent = PDFBoxTools.setLineBreaks(eml.getTo(), width, emailHeaderFontSize, bodyFont);
        List<String> fromContent = PDFBoxTools.setLineBreaks(eml.getFrom(), width, emailHeaderFontSize,
                bodyFont);
        List<String> ccContent = PDFBoxTools.setLineBreaks(eml.getCc(), width, emailHeaderFontSize, bodyFont);
        List<String> bccContent = PDFBoxTools.setLineBreaks(eml.getBcc(), width, emailHeaderFontSize, bodyFont);
        List<String> attachmentContent = PDFBoxTools.setLineBreaks(eml.getAttachments(), width,
                emailHeaderFontSize, bodyFont);
        List<String> subjectContent = PDFBoxTools.setLineBreaks(eml.getSubject(), width, bodyFontSize,
                bodyFont);
        List<String> bodyContent = PDFBoxTools.setLineBreaks(eml.getBody(), width, bodyFontSize, bodyFont);

        //Set Email Header
        contentStream.beginText();
        contentStream.setFont(bodyFont, emailHeaderFontSize);
        contentStream.setNonStrokingColor(Color.BLACK);
        contentStream.newLineAtOffset(startX, startY);

        //Set Date Sent
        if (!"".equals(eml.getSentDate())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("Date Sent: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : sentDateContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }

                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set Date Received
        if (!"".equals(eml.getReceiveDate().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("Date Received: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : recievedDateContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }

                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingBody;
            }
        }
        contentStream.newLineAtOffset(0, -leadingBody);

        //Set From
        if (!"".equals(eml.getFrom().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("From: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : fromContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set To
        if (!"".equals(eml.getTo().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("To: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : toContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set CC
        if (!"".equals(eml.getCc().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("CC: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : ccContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set BCC
        if (!"".equals(eml.getBcc().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("BCC: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : bccContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set AttachmentList
        if (!"".equals(eml.getAttachments().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("Attachments: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : attachmentContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set Subject
        if (!"".equals(eml.getSubject().trim())) {
            contentStream.newLineAtOffset(0, -leadingBody);
            contentStream.newLineAtOffset(0, -leadingBody);
            contentStream.setFont(bodyTitleFont, bodyFontSize);
            contentStream.showText("Subject: ");
            contentStream.newLineAtOffset(0, -leadingBody);
            textYlocation += leadingBody;
            contentStream.setFont(bodyFont, bodyFontSize);
            for (String line : subjectContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingBody);
                textYlocation += leadingBody;
            }
        }
        if (!"".equals(eml.getBody().trim())) {
            // Set Email Body
            contentStream.newLineAtOffset(0, -leadingBody);
            contentStream.setFont(bodyTitleFont, bodyFontSize);
            contentStream.showText("Message: ");
            contentStream.setFont(bodyFont, bodyFontSize);
            contentStream.newLineAtOffset(0, -leadingBody);
            for (String line : bodyContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingBody)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, bodyFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }

                textYlocation += leadingBody;

                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingBody);
            }
            contentStream.endText();

        }
        contentStream.close();
        doc.save(eml.getFilePath() + eml.getFileName());
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
            }
        }
    }
}

From source file:com.fileOperations.ImageToPDF.java

/**
 * create PDF from image and scales it accordingly to fit in a single page
 *
 * @param folderPath String/* w  w  w  . j a v  a  2  s  . c  o m*/
 * @param imageFileName String
 * @return String new filename
 */
public static String createPDFFromImage(String folderPath, String imageFileName) {
    String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf";
    String image = folderPath + imageFileName;
    PDImageXObject pdImage = null;
    File imageFile = null;
    FileInputStream fileStream = null;
    BufferedImage bim = null;

    File attachmentLocation = new File(folderPath);
    if (!attachmentLocation.exists()) {
        attachmentLocation.mkdirs();
    }

    // the document
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    try {
        doc = new PDDocument();
        PDPage page = new PDPage(PDRectangle.LETTER);
        float margin = 72;
        float pageWidth = page.getMediaBox().getWidth() - 2 * margin;
        float pageHeight = page.getMediaBox().getHeight() - 2 * margin;

        if (image.toLowerCase().endsWith(".jpg")) {
            imageFile = new File(image);
            fileStream = new FileInputStream(image);
            pdImage = JPEGFactory.createFromStream(doc, fileStream);
            //            } else if ((image.toLowerCase().endsWith(".tif")
            //                    || image.toLowerCase().endsWith(".tiff"))
            //                    && TIFFCompression(image) == COMPRESSION_GROUP4) {
            //                imageFile = new File(image);
            //                pdImage = CCITTFactory.createFromFile(doc, imageFile);
        } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp")
                || image.toLowerCase().endsWith(".png")) {
            imageFile = new File(image);
            bim = ImageIO.read(imageFile);
            pdImage = LosslessFactory.createFromImage(doc, bim);
        }

        if (pdImage != null) {
            if (pdImage.getWidth() > pdImage.getHeight()) {
                page.setRotation(270);
                PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(),
                        page.getMediaBox().getWidth());
                page.setMediaBox(rotatedPage);
                pageWidth = page.getMediaBox().getWidth() - 2 * margin;
                pageHeight = page.getMediaBox().getHeight() - 2 * margin;
            }
            Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight);
            Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight());
            Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize);
            float startX = page.getMediaBox().getLowerLeftX() + margin;
            float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height;

            doc.addPage(page);
            contentStream = new PDPageContentStream(doc, page);
            contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height);
            contentStream.close();
            doc.save(folderPath + pdfFile);
        }
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
        return "";
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
                return "";
            }
        }
    }
    if (fileStream != null) {
        try {
            fileStream.close();
        } catch (IOException ex) {
            ExceptionHandler.Handle(ex);
            return "";
        }
    }
    if (bim != null) {
        bim.flush();
    }
    if (imageFile != null) {
        imageFile.delete();
    }
    return pdfFile;
}

From source file:com.fileOperations.ImageToPDF.java

/**
 * create PDF from image and scales it accordingly to fit in a single page
 *
 * @param folderPath String/*from w  w w  . j av a  2  s  . c o m*/
 * @param imageFileName String
 * @return String new filename
 */
public static String createPDFFromImageNoDelete(String folderPath, String imageFileName) {
    String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf";
    String image = folderPath + imageFileName;
    PDImageXObject pdImage = null;
    File imageFile = null;
    FileInputStream fileStream = null;
    BufferedImage bim = null;

    File attachmentLocation = new File(folderPath);
    if (!attachmentLocation.exists()) {
        attachmentLocation.mkdirs();
    }

    // the document
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    try {
        doc = new PDDocument();
        PDPage page = new PDPage(PDRectangle.LETTER);
        float margin = 72;
        float pageWidth = page.getMediaBox().getWidth() - 2 * margin;
        float pageHeight = page.getMediaBox().getHeight() - 2 * margin;

        if (image.toLowerCase().endsWith(".jpg")) {
            imageFile = new File(image);
            fileStream = new FileInputStream(image);
            pdImage = JPEGFactory.createFromStream(doc, fileStream);
            //            } else if ((image.toLowerCase().endsWith(".tif")
            //                    || image.toLowerCase().endsWith(".tiff"))
            //                    && TIFFCompression(image) == COMPRESSION_GROUP4) {
            //                imageFile = new File(image);
            //                pdImage = CCITTFactory.createFromFile(doc, imageFile);
        } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp")
                || image.toLowerCase().endsWith(".png")) {
            imageFile = new File(image);
            bim = ImageIO.read(imageFile);
            pdImage = LosslessFactory.createFromImage(doc, bim);
        }

        if (pdImage != null) {
            if (pdImage.getWidth() > pdImage.getHeight()) {
                page.setRotation(270);
                PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(),
                        page.getMediaBox().getWidth());
                page.setMediaBox(rotatedPage);
                pageWidth = page.getMediaBox().getWidth() - 2 * margin;
                pageHeight = page.getMediaBox().getHeight() - 2 * margin;
            }
            Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight);
            Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight());
            Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize);
            float startX = page.getMediaBox().getLowerLeftX() + margin;
            float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height;

            doc.addPage(page);
            contentStream = new PDPageContentStream(doc, page);
            contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height);
            contentStream.close();
            doc.save(folderPath + pdfFile);
        }
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
        return "";
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
                return "";
            }
        }
    }
    if (fileStream != null) {
        try {
            fileStream.close();
        } catch (IOException ex) {
            ExceptionHandler.Handle(ex);
            return "";
        }
    }
    if (bim != null) {
        bim.flush();
    }
    return pdfFile;
}

From source file:com.fileOperations.StampPDF.java

/**
 * This stamps docketed files.//from   w w w .  j a va  2  s.c  om
 *
 * @param file String (full file path)
 * @param docketTime Timestamp
 * @param dept
 */
public static void stampDocument(String file, Timestamp docketTime, String dept) {
    // the document
    PDDocument doc = null;
    try {
        PDFont stampFont = PDType1Font.TIMES_ROMAN;
        float stampFontSize = 14;
        String title = PDFBoxTools.HeaderTimeStamp(docketTime) + " " + dept;
        float titleWidth = stampFont.getStringWidth(title) / 1000 * stampFontSize;
        float titleHeight = stampFont.getFontDescriptor().getFontBoundingBox().getHeight() / 1000
                * stampFontSize;
        int marginTop = 20;

        doc = PDDocument.load(new File(file));

        if (!doc.isEncrypted()) {
            for (int i = 0; i < doc.getPages().getCount(); i++) {
                PDPageContentStream contentStream = null;

                PDPage page = (PDPage) doc.getPages().get(i);

                contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);
                page.getResources().getFontNames();

                contentStream.beginText();
                contentStream.setFont(stampFont, stampFontSize);
                contentStream.setNonStrokingColor(Color.RED);
                contentStream.newLineAtOffset((page.getMediaBox().getWidth() - titleWidth) / 2,
                        page.getMediaBox().getHeight() - marginTop - titleHeight);
                contentStream.showText(title);
                contentStream.endText();

                contentStream.close();
            }
            doc.save(file);
        }
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
            }
        }
    }
}

From source file:com.fileOperations.TXTtoPDF.java

/**
 * Takes the text from the string and insert it into the PDF file
 *
 * @param pdfFile String (path + filename)
 * @param text String (text from document)
 *///  w w w . j a v a  2 s.com
private static void makePDF(String pdfFile, String text) {
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    //Fonts used
    PDFont bodyFont = PDType1Font.TIMES_ROMAN;

    //Font Sizes
    float bodyFontSize = 12;
    float leadingBody = 1.5f * bodyFontSize;

    try {
        //Create Document, Page, Margins.
        doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);
        contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);
        PDRectangle mediabox = page.getMediaBox();
        float margin = 72;
        float width = mediabox.getWidth() - 2 * margin;
        float startX = mediabox.getLowerLeftX() + margin;
        float startY = mediabox.getUpperRightY() - margin;
        float textYlocation = margin;

        //Set Line Breaks
        text = text.replaceAll("[\\p{C}\\p{Z}]", System.getProperty("line.separator")); //strip ZERO WIDTH SPACE
        List<String> textContent = PDFBoxTools.setLineBreaks(text, width, bodyFontSize, bodyFont);

        contentStream.beginText();
        contentStream.setFont(bodyFont, bodyFontSize);
        contentStream.setNonStrokingColor(Color.BLACK);
        contentStream.newLineAtOffset(startX, startY);

        if (!"".equals(text)) {
            for (String line : textContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingBody)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, true, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, bodyFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }

                textYlocation += leadingBody;

                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingBody);
            }
            contentStream.endText();

        }
        contentStream.close();
        doc.save(pdfFile);
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
            }
        }
    }
}

From source file:com.formkiq.core.service.conversion.ConversionServiceTest.java

License:Apache License

/**
 * sample-form2.pdf to PNG.// w w w  . j  a v  a 2 s.c om
 * @throws IOException IOException
 */
@Test
public void testPdfToPngFormatConverter01() throws IOException {
    // given
    byte[] data = Resources.getResourceAsBytes("/sample-form2.pdf");
    PDDocument doc = PDDocument.load(data);

    // when
    ConversionResult result = this.cs.convert(doc, PDF, PNG);

    // then
    doc.close();

    final int datalength = 128000;
    final int dataheight = 1584;
    final int datawidth = 612;
    final int x = 211;
    final int y = 992;

    assertEquals(1, result.getFields().size());
    assertTrue(result.getData().length > datalength);
    assertEquals(dataheight, (int) result.getDataheight());
    assertEquals(datawidth, (int) result.getDatawidth());

    assertEquals(x, (int) result.getFields().get(0).getX());
    assertEquals(y, (int) result.getFields().get(0).getY());
}

From source file:com.formkiq.core.service.entry.WorkflowEntryFlowEventProcessor.java

License:Apache License

/**
 * Render PDF to PNG.//from w ww . j a  v a 2s .co  m
 * @param flow {@link WebFlow}
 * @return {@link String} nothing just to prevent 302.
 * @throws IOException IOException
 */
@Transactional
public String eventIdrenderimage(final WebFlow flow) throws IOException {

    ConversionResult cpng = flow.getParameter(PDFCONV);

    if (cpng == null) {

        ArchiveDTO archive = flow.getData();
        this.folderService.createWorkflowOutput(archive);

        if (archive.getPDF().isEmpty()) {
            throw new PreconditionFailedException("No PDF Found");
        }

        if (archive.getPDF().size() > 1) {
            throw new PreconditionFailedException(archive.getPDF().size() + " PDF(s) Found");
        }

        byte[] data = archive.getPDF().values().iterator().next();
        PDDocument doc = PDDocument.load(data);

        try {
            cpng = new ConversionService().convert(doc, PDF, PNG);
            flow.setParameter(PDFCONV, cpng);
        } finally {
            doc.close();
        }
    }

    return "";
}

From source file:com.formkiq.core.service.generator.docx4j.WorkflowOutputWordDocxTest.java

License:Apache License

/**
 * create PDF output from DOCX.//from  w w w.j av  a 2  s  . c  o  m
 * @throws Exception Exception
 */
@Test
public void testCreateOutput02() throws Exception {
    // given
    WorkflowOutputDocumentType outDocType = PDF;
    ArchiveDTO archive = new ArchiveDTO();

    // when
    String docname = createOutputDoc(archive, outDocType);

    // then
    assertNull(archive.getObject(docname + ".docx"));
    assertNotNull(archive.getObject(docname + ".pdf"));

    byte[] data = archive.getObject(docname + ".pdf");

    String text = Strings.toString(data);
    assertTrue(text.startsWith("%PDF-1.4"));

    PDDocument doc = PDDocument.load(data);

    text = Strings.toString(new ConversionService().convert(doc, PDF, HTML).getData());

    assertTrue(text.contains("Jan"));
    assertTrue(text.contains("2017"));
    assertTrue(text.contains("12"));
    assertFalse(text.contains("DAY"));
    assertFalse(text.contains("MONTH"));
    assertFalse(text.contains("YEAR"));
    assertTrue(text.contains("Johnny Smith"));

    doc.close();
}

From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java

License:Apache License

/**
 * Do Partial PDF Save. This save works when updating Signature fields.
 * @param docBytes byte[]/*from  w ww  .j  ava2s.c om*/
 * @param archive {@link ArchiveDTO}
 * @param output {@link WorkflowOutputPdfForm}
 * @throws IOException IOException
 */
private void doSignaturePdfSave(final byte[] docBytes, final ArchiveDTO archive,
        final WorkflowOutputPdfForm output) throws IOException {

    boolean signed = false;
    List<SignatureOptions> signatureOptions = new ArrayList<>();
    PDDocument doc = loadPDF(docBytes);

    try {

        PDDocumentCatalog docCatalog = doc.getDocumentCatalog();
        PDAcroForm pdform = docCatalog.getAcroForm();

        for (WorkflowOutputFormField ofield : output.getFields()) {

            Optional<FormJSON> form = findForm(archive, ofield);
            Optional<FormJSONField> field = findFormField(form, ofield);

            if (form.isPresent() && field.isPresent()) {

                String value = field.get().getValue();

                PDField pfield = pdform.getField(ofield.getDocumentfieldname());

                if (pfield != null && pfield instanceof PDSignatureField) {

                    byte[] bs = form.get().getAssetData().get(value);
                    if (bs != null) {

                        try {
                            InputStream is = new ByteArrayInputStream(bs);

                            signatureOptions.add(setValue(doc, (PDSignatureField) pfield, is));

                            signed = true;

                        } catch (IllegalStateException e) {
                            LOG.log(Level.WARNING, "unable to set signature", e);
                        }
                    }
                }
            }
        }

        if (signed) {

            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            doc.saveIncremental(bs);
            bs.close();

            String pdfname = output.getName();
            archive.addPDF(pdfname + ".pdf", bs.toByteArray());
        }

        for (SignatureOptions sigOption : signatureOptions) {
            IOUtils.closeQuietly(sigOption);
        }

    } finally {
        doc.close();
    }
}

From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java

License:Apache License

/**
 * Do Full PDF Save. This save works when updating the values of fields.
 * @param docBytes byte[]/*from  w  ww . j av a2 s . c o m*/
 * @param archive {@link ArchiveDTO}
 * @param output {@link WorkflowOutputPdfForm}
 * @return boolean - whether signature fields are found
 * @throws IOException IOException
 */
private boolean dofullPDFSave(final byte[] docBytes, final ArchiveDTO archive,
        final WorkflowOutputPdfForm output) throws IOException {

    boolean hasSignatures = false;
    PDDocument doc = loadPDF(docBytes);

    try {

        PDDocumentCatalog docCatalog = doc.getDocumentCatalog();
        PDAcroForm pdform = docCatalog.getAcroForm();

        for (WorkflowOutputFormField ofield : output.getFields()) {

            Optional<FormJSON> form = findForm(archive, ofield);
            Optional<FormJSONField> field = findFormField(form, ofield);

            if (form.isPresent() && field.isPresent()) {

                PDField pdfield = pdform.getField(ofield.getDocumentfieldname());

                if (pdfield != null) {

                    if (pdfield instanceof PDSignatureField) {
                        hasSignatures = true;
                    } else {

                        String value = field.get().getValue();
                        List<String> values = field.get().getValues();

                        if (!isEmpty(values)) {
                            for (String val : values) {
                                pdfield.setValue(extractLabelAndValue(val).getRight());
                            }
                        } else if (!isEmpty(value)) {
                            value = extractLabelAndValue(value).getRight();
                            pdfield.setValue(value);
                        }
                    }
                }
            }
        }

        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        doc.save(bs);
        bs.close();

        String pdfname = output.getName();
        archive.addPDF(pdfname + ".pdf", bs.toByteArray());

        return hasSignatures;

    } finally {
        doc.close();
    }

}