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

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

Introduction

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

Prototype

public PDDocument() 

Source Link

Document

Creates an empty PDF document.

Usage

From source file:com.fileOperations.EmailBodyToPDF.java

/**
 * Places the text of the email into the PDF
 *
 * @param eml EmailBodyPDF/*from w ww .j  a  v  a2  s  . c om*/
 */
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/*from   www.j a va 2s  .c om*/
 * @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  ww  w. j  a  v a  2s . co 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.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  ww  .  ja v a  2s .c o  m
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.foc.vaadin.gui.pdfGenerator.FocXmlPDFParser.java

License:Apache License

@Override
public PDDocument getPDDocument() {
    if (document == null) {
        try {//from   w w w . j  av  a2  s.com
            document = new PDDocument();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return document;
}

From source file:com.github.gujou.deerbelling.sonarqube.service.PdfApplicationGenerator.java

License:Open Source License

public static File generateFile(Project sonarProject, FileSystem sonarFileSystem, String sonarUrl,
        String sonarLogin, String sonarPassword, Map<String, Measure> sonarMeasures) {

    Resources sonarResources = ResourceGateway.getOpenIssues(sonarProject.getKey(), sonarUrl, sonarLogin,
            sonarPassword);/*from ww  w  .j a  v  a 2  s.  co  m*/

    // Only one resource => call with sonarProject.getKey()
    Resource projectResource = sonarResources.getResource().get(0);

    for (Measure measure : projectResource.getMsr()) {

        System.out.println(measure.getKey() + " " + measure.getVal());

        sonarMeasures.put(measure.getKey(), measure);
    }

    String projectName = sonarProject.getName().replaceAll("[^A-Za-z0-9 ]", " ").trim().replaceAll(" +", " ");

    String filePath = sonarFileSystem.workDir().getAbsolutePath() + File.separator + "application_report_"
            + sonarProject.getEffectiveKey().replace(':', '-') + "."
            + ReportsKeys.APPLICATION_REPORT_TYPE_PDF_EXTENSION;

    File file = new File(filePath);

    String fontfile = "font/OpenSans-Regular.ttf";

    PDDocument doc = new PDDocument();
    try {

        initNewPage(doc);

        PDSimpleFont font = PDType1Font.TIMES_BOLD;
        PDSimpleFont fontItalic = PDType1Font.TIMES_BOLD_ITALIC;

        PDImageXObject smileLogo = createFromFile("/images/Logo_Smile.png", doc);

        leftImage(smileLogo, page, doc, 80, 166);

        positionHeight = (int) (page.getMediaBox().getHeight() / 2) - 65;

        centerText("Indicateurs du projet", font, 45, page, doc);

        int heightProjectName = maximizeText(projectName, font, page, doc);

        positionHeight = (int) (page.getMediaBox().getHeight()) - 280 + heightProjectName;

        positionLogoWidth = (int) (page.getMediaBox().getWidth() / 2) - 100;
        positionTitleWidth = (int) (page.getMediaBox().getWidth() / 2) - 100;

        PDImageXObject icon_lines = createFromFile("/images/Lines-50.png", doc);

        PDImageXObject icon_author = createFromFile("/images/Typewriter_With_Paper-50.png", doc);

        PDImageXObject icon_version = createFromFile("/images/Versions-50.png", doc);

        PDImageXObject icon_date = createFromFile("/images/Date_To-50.png", doc);

        PDImageXObject icon_ncloc = createFromFile("/images/CodeLines-52.png", doc);

        PDImageXObject icon_folders = createFromFile("/images/Folder-50.png", doc);

        PDImageXObject icon_packages = createFromFile("/images/Box-52.png", doc);

        PDImageXObject icon_classes = createFromFile("/images/CodeFile-50.png", doc);

        PDImageXObject icon_files = createFromFile("/images/File-50.png", doc);

        PDImageXObject icon_methods = createFromFile("/images/Settings_3-50.png", doc);

        PDImageXObject icon_accessors = createFromFile("/images/Accessors-50.png", doc);

        PDImageXObject icon_api = createFromFile("/images/API_Settings-50.png", doc);

        PDImageXObject icon_keyring = createFromFile("/images/Keys.png", doc);

        PDImageXObject icon_bug = createFromFile("/images/Bug-50.png", doc);

        PDImageXObject icon_balance = createFromFile("/images/Scales-50.png", doc);

        PDImageXObject icon_wightBugs = createFromFile("/images/Weight-Bug-50.png", doc);

        PDImageXObject icon_poison = createFromFile("/images/Poison-50.png", doc);

        PDImageXObject icon_fire = createFromFile("/images/Campfire-50.png", doc);

        PDImageXObject icon_major = createFromFile("/images/Error-50.png", doc);

        PDImageXObject icon_minor = createFromFile("/images/Attention-51.png", doc);

        PDImageXObject icon_info = createFromFile("/images/Info-50.png", doc);

        PDImageXObject icon_ok = createFromFile("/images/Ok-50.png", doc);

        PDImageXObject icon_open = createFromFile("/images/Open_Sign-50.png", doc);

        PDImageXObject icon_confirmed = createFromFile("/images/Law-50.png", doc);

        PDImageXObject icon_debt = createFromFile("/images/Banknotes-52.png", doc);

        PDImageXObject icon_codeGenerated = createFromFile("/images/CodeFactory-50.png", doc);

        PDImageXObject icon_linesGenerated = createFromFile("/images/LineFactory-50.png", doc);

        PDImageXObject icon_screen = createFromFile("/images/Screen_TV-52.png", doc);

        PDImageXObject icon_screenSimple = createFromFile("/images/Screen_Pion-52.png", doc);

        PDImageXObject icon_screenMedium = createFromFile("/images/Screen_Cheval-52.png", doc);

        PDImageXObject icon_screenComplex = createFromFile("/images/Screen_Queen-52.png", doc);

        PDImageXObject icon_xmlTotal = createFromFile("/images/Conf_File-50.png", doc);

        PDImageXObject icon_xmlSimple = createFromFile("/images/Conf_File_simple-50.png", doc);

        PDImageXObject icon_xmlMedium = createFromFile("/images/Conf_File_medium-50.png", doc);

        PDImageXObject icon_xmlComplex = createFromFile("/images/Conf_File_complex-50.png", doc);

        PDImageXObject icon_mulesoftOut = createFromFile("/images/icon-mulesoftm-out.png", doc);
        PDImageXObject icon_mulesoftIn = createFromFile("/images/icon-mulesoftm-in.png", doc);

        PDImageXObject icon_mulesoftFlow = createFromFile("/images/icon-mulesoftm-flow.png", doc);

        PDImageXObject icon_complexity = createFromFile("/images/Frankensteins_Monster-48.png", doc);

        PDImageXObject icon_complexityClass = createFromFile("/images/ComplexCodeFile-50.png", doc);

        PDImageXObject icon_complexityMethod = createFromFile("/images/WolfSettings-50.png", doc);

        PDImageXObject icon_complexityFile = createFromFile("/images/FreddyFile-50.png", doc);

        PDImageXObject icon_comments = createFromFile("/images/Quote-50.png", doc);

        PDImageXObject icon_javadoc = createFromFile("/images/Comments-API.png", doc);

        PDImageXObject icon_tests_fail = createFromFile("/images/Dizzy_Person_Filled-50.png", doc);

        PDImageXObject icon_tests_skip = createFromFile("/images/Fast_Forward-50.png", doc);

        PDImageXObject icon_tests_error = createFromFile("/images/Explosion-50.png", doc);

        PDImageXObject icon_tests = createFromFile("/images/Search-52.png", doc);

        PDImageXObject icon_tests_success = createFromFile("/images/Goal-50.png", doc);

        PDImageXObject icon_conditions_cover = createFromFile("/images/Waning_Gibbous-52.png", doc);

        PDImageXObject icon_tests_cover = createFromFile("/images/Checklist-50.png", doc);

        PDImageXObject icon_vulnerability_high = createFromFile("/images/Shark-52.png", doc);

        PDImageXObject icon_vulnerability_medium = createFromFile("/images/Bee-50.png", doc);

        PDImageXObject icon_vulnerability_low = createFromFile("/images/Black_Cat-50.png", doc);

        PDImageXObject icon_declared = createFromFile("/images/Sugar_Cubes-64.png", doc);

        PDImageXObject icon_unused = createFromFile("/images/Litter_Disposal-50.png", doc);

        PDImageXObject icon_undeclared = createFromFile("/images/Move_by_Trolley-50.png", doc);

        PDImageXObject icon_filecycle = createFromFile("/images/FileCycle.png", doc);

        PDImageXObject icon_packagecycle = createFromFile("/images/PackageCycle.png", doc);

        PDImageXObject icon_cut_files = createFromFile("/images/Cut-50.png", doc);

        PDImageXObject icon_chain = createFromFile("/images/Link-52.png", doc);

        PDImageXObject icon_cut_directories = createFromFile("/images/Chainsaw-52.png", doc);

        PDImageXObject icon_duplicate = createFromFile("/images/Feed_Paper-50.png", doc);

        PDImageXObject icon_duplicate_lines = createFromFile("/images/Line-Spacing-icon.png", doc);

        PDImageXObject icon_duplicate_packages = createFromFile("/images/DuplicateBlocks2.png", doc);

        PDImageXObject icon_dev_count = createFromFile("/images/Workers_Male-50.png", doc);
        PDImageXObject icon_dev_best = createFromFile("/images/Weightlifting_Filled-50.png", doc);
        PDImageXObject icon_dev_issues = createFromFile("/images/Full_of_Shit-50.png", doc);

        attribute(icon_author, 22, 22, " Guillaume Jourdan", fontItalic, 15, doc, DEFAULT_TEXT_COLOR);
        attribute(icon_version, 22, 22, " Version 1.0", fontItalic, 15, doc, DEFAULT_TEXT_COLOR); // TODO
        // switch
        // field
        // &
        // value
        // :
        // resource
        // =>
        // version

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.FRENCH);
        attribute(icon_date, 22, 22, simpleDateFormat.format(new Date()), fontItalic, 15, doc,
                DEFAULT_TEXT_COLOR); // TODO
        // switch
        // field
        // &
        // value
        // :
        // resource
        // =>
        // date

        initNewPage(doc);

        title("Project Sizing", font, 26, doc);

        attribute(icon_ncloc, 22, 22, sonarMeasures.get("ncloc"), true, " lines of code", font, 15, doc); // ncloc
        attribute(icon_lines, 22, 22, sonarMeasures.get("lines"), true, " lines", font, 15, doc); // lines
        // =>
        // TODO
        attribute(icon_classes, 22, 22, sonarMeasures.get("classes"), true, " classes", font, 15, doc); // classes
        attribute(icon_files, 22, 22, sonarMeasures.get("files"), true, " files", font, 15, doc); // files
        // =>
        // TODO
        attribute(icon_folders, 22, 22, sonarMeasures.get("directories"), true, " directories", font, 15, doc); // directories
        attribute(icon_packages, 22, 22, sonarMeasures.get("projects"), true, " modules", font, 15, doc); // projects
        attribute(icon_methods, 22, 22, sonarMeasures.get("functions"), true, " methods", font, 15, doc); // functions
        attribute(icon_accessors, 22, 22, sonarMeasures.get("accessors"), true, " getters and setters", font,
                15, doc); // accessors
        attribute(icon_api, 22, 22, sonarMeasures.get("public_api"), true, "  public API", font, 15, doc); // public_api
        attribute(icon_keyring, 22, 22, sonarMeasures.get("statements"), true, " statements", font, 15, doc); // statements
        attribute(icon_codeGenerated, 22, 22, sonarMeasures.get("generated_ncloc"), true,
                " generated code lines", font, 15, doc); // generated_ncloc
        attribute(icon_linesGenerated, 22, 22, sonarMeasures.get("generated_lines"), true, " generated lines",
                font, 15, doc); // generated_lines

        Measure totalPages = sonarMeasures.get("total_pages");
        Measure simplePages = sonarMeasures.get("simple_pages");
        Measure mediumPages = sonarMeasures.get("medium_pages");
        Measure complexPages = sonarMeasures.get("complex_pages");

        if (totalPages != null) {
            attribute(icon_screen, 22, 22, totalPages, true, totalPages.getLabel(), font, 15, doc);
        }
        if (simplePages != null) {
            attribute(icon_screenSimple, 22, 22, simplePages, true, simplePages.getLabel(), font, 15, doc);
        }
        if (mediumPages != null) {
            attribute(icon_screenMedium, 22, 22, mediumPages, true, mediumPages.getLabel(), font, 15, doc);
        }
        if (complexPages != null) {
            attribute(icon_screenComplex, 22, 22, complexPages, true, complexPages.getLabel(), font, 15, doc);
        }

        Measure xmlNbTotal = sonarMeasures.get("xmlNbTotal");
        Measure xmlSimpleNbTotal = sonarMeasures.get("xmlSimpleNbTotal");
        Measure xmlMediumNbTotal = sonarMeasures.get("xmlMediumNbTotal");
        Measure xmlComplexNbTotal = sonarMeasures.get("xmlComplexNbTotal");
        Measure muleOutputField = sonarMeasures.get("muleOutputField");
        Measure muleNbRequestField = sonarMeasures.get("muleNbRequestField");
        Measure muleNbFlow = sonarMeasures.get("muleNbFlow");
        Measure muleNbSubFlow = sonarMeasures.get("muleNbSubFlow");

        if (xmlNbTotal != null) {
            attribute(icon_xmlTotal, 22, 22, xmlNbTotal, true, xmlNbTotal.getLabel(), font, 15, doc);
        }
        if (xmlSimpleNbTotal != null) {
            attribute(icon_xmlSimple, 22, 22, xmlSimpleNbTotal, true, xmlSimpleNbTotal.getLabel(), font, 15,
                    doc);
        }
        if (xmlMediumNbTotal != null) {
            attribute(icon_xmlMedium, 22, 22, xmlMediumNbTotal, true, xmlMediumNbTotal.getLabel(), font, 15,
                    doc);
        }
        if (xmlComplexNbTotal != null) {
            attribute(icon_xmlComplex, 22, 22, xmlComplexNbTotal, true, xmlComplexNbTotal.getLabel(), font, 15,
                    doc);
        }
        if (muleOutputField != null) {
            attribute(icon_mulesoftOut, 22, 22, muleOutputField, true, muleOutputField.getLabel(), font, 15,
                    doc);
        }
        if (muleNbRequestField != null) {
            attribute(icon_mulesoftIn, 22, 22, muleNbRequestField, true, muleNbRequestField.getLabel(), font,
                    15, doc);
        }
        if (muleNbFlow != null) {
            attribute(icon_mulesoftFlow, 22, 22, muleNbFlow, true, muleNbFlow.getLabel(), font, 15, doc);
        }
        if (muleNbSubFlow != null) {
            attribute(icon_mulesoftFlow, 22, 22, muleNbSubFlow, true, muleNbSubFlow.getLabel(), font, 15, doc);
        }

        title("Design", font, 26, doc);
        attribute(icon_packagecycle, 22, 22, sonarMeasures.get("package_cycles"), true,
                " package cycles detected", font, 15, doc); // package_cycles
        attribute(icon_cut_files, 22, 22, sonarMeasures.get("package_tangles"), true,
                " file dep. to cut cycles ", font, 15, doc, sonarMeasures.get("package_tangle_index"), true); // package_tangles
        // +
        // TODO
        // package_tangle_index
        // X
        attribute(icon_cut_directories, 22, 22, sonarMeasures.get("package_feedback_edges"), true,
                " package dep. to cut cycles", font, 15, doc); // package_feedback_edges
        attribute(icon_chain, 22, 22, sonarMeasures.get("package_edges_weight"), true,
                " file dep. betw. packages", font, 15, doc); // package_edges_weight X

        title("Complexity", font, 26, doc);
        attribute(icon_complexity, 22, 22, sonarMeasures.get("complexity"), true, " complexity index", font, 15,
                doc); // complexity
        attribute(icon_complexityClass, 22, 22, sonarMeasures.get("class_complexity"), true,
                " complexity index by class", font, 15, doc); // class_complexity
        attribute(icon_complexityFile, 22, 22, sonarMeasures.get("file_complexity"), true,
                " complexity index by file", font, 15, doc); // file_complexity
        attribute(icon_complexityMethod, 22, 22, sonarMeasures.get("function_complexity"), true,
                " complexity index by method", font, 15, doc); // function_complexity

        title("Duplications", font, 26, doc);
        attribute(icon_duplicate_lines, 22, 22, sonarMeasures.get("duplicated_lines"), true,
                " duplicated lines", font, 15, doc, sonarMeasures.get("duplicated_lines_density"), true); // duplicated_lines
        // +
        // duplicated_lines_density
        attribute(icon_duplicate, 22, 22, sonarMeasures.get("duplicated_files"), true, " involved files", font,
                15, doc); // duplicated_files
        attribute(icon_duplicate_packages, 22, 22, sonarMeasures.get("duplicated_blocks"), true,
                " duplicated blocks", font, 15, doc); // duplicated_blocks

        title("Sonarqube Issues", font, 26, doc);

        attribute(icon_bug, 22, 22, sonarMeasures.get("violations"), true, " issues", font, 15, doc); // violations
        // +
        // new
        // method
        // for
        // new_violations
        attribute(icon_poison, 22, 22, sonarMeasures.get("blocker_violations"), true, " blocker issues", font,
                15, doc); // blocker_violations + new method for
                                                                                                                                 // new_blocker_violations
        attribute(icon_fire, 22, 22, sonarMeasures.get("critical_violations"), true, " critical issues", font,
                15, doc); // critical_violations + new method for
                                                                                                                                 // new_critical_violations
        attribute(icon_major, 22, 22, sonarMeasures.get("major_violations"), true, " major issues", font, 15,
                doc); // major_violations
        // +
        // new
        // method
        // for
        // new_major_violations
        attribute(icon_minor, 22, 22, sonarMeasures.get("minor_violations"), true, " minor issues", font, 15,
                doc); // minor_violations
        // +
        // new
        // method
        // for
        // new_minor_violations
        // attribute(icon_info, 22, 22, "533", " info issues", font, 15,
        // doc); // info_violations + new method for new_info_violations
        // attribute(icon_ok, 22, 22, "533", " false positive issues", font,
        // 15, doc); // false_positive_issues
        // attribute(icon_open, 22, 22, "533", " open issues", font, 15,
        // doc); // open_issues
        // attribute(icon_confirmed, 22, 22, "533", " confirmed issues",
        // font, 15, doc); // confirmed_issues
        // attribute(icon_open, 22, 22, "533", " reopened issues", font, 15,
        // doc); // reopened_issues
        // attribute(icon_wightBugs, 22, 22, "533", " weighted issues",
        // font, 15, doc); // weighted_violations
        // attribute(icon_balance, 22, 22, "533", " rules compliance index",
        // font, 15, doc); // violations_density

        Measure squaleIndexMeasure = sonarMeasures.get("sqale_index");
        if (squaleIndexMeasure != null) {
            attribute(icon_debt, 22, 22, squaleIndexMeasure.getFrmt_val(), " Sqale technical debt", font, 15,
                    doc, null, false, SMILE_ORANGE_COLOR); // sqale_index
        }

        title("Documentation", font, 26, doc);

        attribute(icon_comments, 22, 22, sonarMeasures.get("comment_lines"), true, " comment lines", font, 15,
                doc, sonarMeasures.get("comment_lines_density"), true); // comment_lines
        // +
        // comment_lines_density

        Measure publicApiUndocMeasure = sonarMeasures.get("public_undocumented_api");

        if (publicApiUndocMeasure != null) {
            String publicApiUndocDensity = "100";
            Measure publicApiDocDensityMeasure = sonarMeasures.get("public_documented_api_density");
            if (publicApiDocDensityMeasure != null) {
                publicApiUndocDensity = decimalFormat.format(
                        100.0 - Float.parseFloat(sonarMeasures.get("public_documented_api_density").getVal()));
            }

            attribute(icon_javadoc, 22, 22, publicApiUndocMeasure, true, " public undoc. API", font, 15, doc,
                    new Measure(publicApiUndocDensity), true); // public_undocumented_api
            // + (1
            // -
            // public_documented_api_density
            // %)
        }
        title("OWASP plugin", font, 26, doc);

        attribute(icon_vulnerability_high, 22, 22, sonarMeasures.get("high_severity_vulns"), true,
                " high dep. vulnerabilities", font, 15, doc);
        attribute(icon_vulnerability_medium, 22, 22, sonarMeasures.get("medium_severity_vulns"), true,
                " medium dep. vulnerabilities", font, 15, doc);
        attribute(icon_vulnerability_low, 22, 22, sonarMeasures.get("low_severity_vulns"), true,
                " low dep. vulnerabilities", font, 15, doc);

        title("Unit Test", font, 26, doc);

        Measure testsMeasure = sonarMeasures.get("tests");

        if (testsMeasure == null) {
            attribute(icon_tests, 22, 22, "0", " unit tests", font, 15, doc, null, false, SMILE_ORANGE_COLOR);
            attribute(icon_tests_cover, 22, 22, "0", " covered lines", font, 15, doc, "0", true,
                    SMILE_ORANGE_COLOR);
        } else {
            attribute(icon_tests, 22, 22, testsMeasure, true, " unit tests", font, 15, doc);
            try {
                int nbTests = (int) Double.parseDouble(testsMeasure.getVal());
                Measure failureTestsMeasure = sonarMeasures.get("test_failures");
                Measure errorTestsMeasure = sonarMeasures.get("test_errors");
                int failureTests = failureTestsMeasure != null
                        ? (int) Double.parseDouble(failureTestsMeasure.getVal())
                        : 0;
                int errorTests = errorTestsMeasure != null
                        ? (int) Double.parseDouble(errorTestsMeasure.getVal())
                        : 0;
                int successTests = nbTests - failureTests - errorTests;
                float errorPercent = (errorTests * 100f) / nbTests;
                float failurePercent = (failureTests * 100f) / nbTests;

                Measure successPercentMeasure = sonarMeasures.get("test_success_density");
                String successPercent = successPercentMeasure != null ? successPercentMeasure.getVal()
                        : decimalFormat.format((successTests * 100) / nbTests);

                attribute(icon_tests_success, 22, 22, Integer.valueOf(successTests).toString(),
                        " tests in success", font, 15, doc, successPercent, true, SMILE_ORANGE_COLOR);
                attribute(icon_tests_fail, 22, 22, Integer.valueOf(failureTests).toString(),
                        " tests in failure", font, 15, doc, decimalFormat.format(failurePercent), true,
                        SMILE_ORANGE_COLOR);
                attribute(icon_tests_error, 22, 22, Integer.valueOf(errorTests).toString(), " tests in error",
                        font, 15, doc, decimalFormat.format(errorPercent), true, SMILE_ORANGE_COLOR);

                Measure coveragePercentMeasure = sonarMeasures.get("line_coverage");
                Measure uncoverMeasure = sonarMeasures.get("uncovered_lines");
                Measure totalLineToCoverMeasure = sonarMeasures.get("lines_to_cover");
                int uncover = uncoverMeasure != null ? (int) Double.parseDouble(uncoverMeasure.getVal()) : 0;
                int totalLineToCover = totalLineToCoverMeasure != null
                        ? (int) Double.parseDouble(totalLineToCoverMeasure.getVal())
                        : 0;
                if (coveragePercentMeasure != null) {
                    attribute(icon_tests_cover, 22, 22, Integer.valueOf(totalLineToCover - uncover).toString(),
                            " covered lines", font, 15, doc, coveragePercentMeasure.getVal(), true,
                            SMILE_ORANGE_COLOR);
                } else {
                    attribute(icon_tests_cover, 22, 22, "0", " covered lines", font, 15, doc, "0", true,
                            SMILE_ORANGE_COLOR);
                }

            } catch (NumberFormatException nfe) {
                System.err.println(nfe);
                nfe.printStackTrace();
            }
        }

        // attribute(icon_tests, 22, 22, sonarMeasures.get("tests"), " unit
        // tests", font, 15, doc); //tests + TODO test_execution_time
        // attribute(icon_tests_success, 22, 22, "0", " tests in success",
        // font, 15, doc, sonarMeasures.get("test_success_density"), true);
        // // calcul success + test_success_density
        // attribute(icon_tests_fail, 22, 22, "0", " tests in failure",
        // font, 15, doc); // test_failures + calcul fail density
        // attribute(icon_tests_error, 22, 22, "0", " tests in error", font,
        // 15, doc); // test_errors + calcul error density
        // attribute(icon_tests_skip, 22, 22, "0", " tests skipped", font,
        // 15, doc); // skipped_tests
        // attribute(icon_tests_cover, 22, 22,
        // sonarMeasures.get("line_coverage"), " covered lines", font, 15,
        // doc, sonarMeasures.get("lines_to_cover"), true); // line_coverage
        // => lines_to_cover
        // attribute(icon_conditions_cover, 22, 22, "4450", " uncovered
        // conditions", font, 15, doc, "85", true); // uncovered_conditions
        // + (100 - branch_coverage)

        // add XMP metadata
        XMPMetadata xmp = XMPMetadata.createXMPMetadata();

        try {
            DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema();
            dc.setTitle(filePath);

            PDFAIdentificationSchema id = xmp.createAndAddPFAIdentificationSchema();
            id.setPart(1);
            id.setConformance("B");

            XmpSerializer serializer = new XmpSerializer();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            serializer.serialize(xmp, baos, true);

            PDMetadata metadata = new PDMetadata(doc);
            metadata.importXMPMetadata(baos.toByteArray());
            doc.getDocumentCatalog().setMetadata(metadata);
        } catch (BadFieldValueException e) {

            e.printStackTrace();
            // // won't happen here, as the provided value is valid
            // throw new IllegalArgumentException(e);
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // sRGB output intent
        // InputStream colorProfile =
        // CreatePDFA.class.getResourceAsStream("/usr/share/color/icc/colord/BestRGB.icc");
        // // /usr/share/color/icc/colord/sRGB.icc

        FileInputStream iccFile = new FileInputStream(new File("/usr/share/color/icc/colord/BestRGB.icc"));
        // PDOutputIntent intent = new PDOutputIntent(doc, colorProfile);
        PDOutputIntent intent = new PDOutputIntent(doc, iccFile);
        intent.setInfo("sRGB IEC61966-2.1");
        intent.setOutputCondition("sRGB IEC61966-2.1");
        intent.setOutputConditionIdentifier("sRGB IEC61966-2.1");
        intent.setRegistryName("http://www.color.org");
        doc.getDocumentCatalog().addOutputIntent(intent);

        doc.save(file);
    } catch (IOException e1) {

        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {

        IOUtils.closeQuietly(doc);
    }
    return file;
}

From source file:com.helger.pdflayout.PageLayoutPDF.java

License:Apache License

/**
 * Render this layout to an OutputStream.
 *
 * @param aCustomizer//from ww  w. ja  va  2  s.c o  m
 *        The customizer to be invoked before the document is written to the
 *        stream. May be <code>null</code>.
 * @param aOS
 *        The output stream to write to. May not be <code>null</code>. Is
 *        closed automatically.
 * @throws PDFCreationException
 *         In case of an error
 */
public void renderTo(@Nullable final IPDDocumentCustomizer aCustomizer,
        @Nonnull @WillClose final OutputStream aOS) throws PDFCreationException {
    // create a new document
    PDDocument aDoc = null;

    try {
        aDoc = new PDDocument();

        // Set document properties
        {
            final PDDocumentInformation aProperties = new PDDocumentInformation();
            if (StringHelper.hasText(m_sDocumentAuthor))
                aProperties.setAuthor(m_sDocumentAuthor);
            if (m_aDocumentCreationDate != null)
                aProperties.setCreationDate(m_aDocumentCreationDate);
            if (StringHelper.hasText(m_sDocumentCreator))
                aProperties.setCreator(m_sDocumentCreator);
            if (StringHelper.hasText(m_sDocumentTitle))
                aProperties.setTitle(m_sDocumentTitle);
            if (StringHelper.hasText(m_sDocumentKeywords))
                aProperties.setKeywords(m_sDocumentKeywords);
            if (StringHelper.hasText(m_sDocumentSubject))
                aProperties.setSubject(m_sDocumentSubject);
            aProperties.setProducer("ph-pdf-layout - https://github.com/phax/ph-pdf-layout");
            // add the created properties
            aDoc.setDocumentInformation(aProperties);
        }

        // Prepare all page sets
        final PageSetPrepareResult[] aPRs = new PageSetPrepareResult[m_aPageSets.size()];
        int nPageSetIndex = 0;
        int nTotalPageCount = 0;
        for (final PLPageSet aPageSet : m_aPageSets) {
            final PageSetPrepareResult aPR = aPageSet.prepareAllPages();
            aPRs[nPageSetIndex] = aPR;
            nTotalPageCount += aPR.getPageCount();
            nPageSetIndex++;
        }

        // Start applying all page sets
        nPageSetIndex = 0;
        int nTotalPageIndex = 0;
        for (final PLPageSet aPageSet : m_aPageSets) {
            final PageSetPrepareResult aPR = aPRs[nPageSetIndex];
            aPageSet.renderAllPages(aPR, aDoc, m_bDebug, nPageSetIndex, nTotalPageIndex, nTotalPageCount);
            // Inc afterwards
            nTotalPageIndex += aPR.getPageCount();
            nPageSetIndex++;
        }

        // Customize the whole document (optional)
        if (aCustomizer != null)
            aCustomizer.customizeDocument(aDoc);

        // save document to output stream
        aDoc.save(aOS);

        if (s_aLogger.isDebugEnabled())
            s_aLogger.debug("PDF successfully created");
    } catch (final IOException ex) {
        throw new PDFCreationException("IO Error", ex);
    } catch (final Throwable t) {
        throw new PDFCreationException("Internal error", t);
    } finally {
        // close document
        if (aDoc != null) {
            try {
                aDoc.close();
            } catch (final IOException ex) {
                s_aLogger.error("Failed to close PDF document " + aDoc, ex);
            }
        }

        // Necessary in case of an exception
        StreamUtils.close(aOS);
    }
}

From source file:com.hostandguest.services.FXML_BookingListController.java

private boolean saveToPDF(Booking booking) {
    try {/*from w  w  w.j  av a 2s . co m*/
        // get the user to provide save directory
        DirectoryChooser directoryChooser = new DirectoryChooser();

        directoryChooser.setTitle("Choose Save Location");

        File selectedDir = directoryChooser.showDialog(new Stage());

        String fileName = booking.getGuest().getLast_name() + " " + booking.getGuest().getFirst_name() + " "
                + booking.getBookingDate().toString() + ".pdf";

        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();

        doc.addPage(page);

        PDPageContentStream content = new PDPageContentStream(doc, page);

        // setting content
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 26);
        content.newLineAtOffset(220, 750);
        content.showText("Reservation Form");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 16);
        content.newLineAtOffset(80, 700);
        content.showText("Name : ");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 14);
        content.newLineAtOffset(250, 700);
        content.showText(booking.getGuest().getLast_name() + " " + booking.getGuest().getFirst_name());
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 16);
        content.newLineAtOffset(80, 650);
        content.showText("Reservation Date : ");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 14);
        content.newLineAtOffset(250, 650);
        content.showText(booking.getBookingDate().toString());
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 16);
        content.newLineAtOffset(80, 600);
        content.showText("Term : ");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 14);
        content.newLineAtOffset(250, 600);
        content.showText(String.valueOf(booking.getTerm()));
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 16);
        content.newLineAtOffset(80, 550);
        content.showText("Number of Rooms : ");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 14);
        content.newLineAtOffset(250, 550);
        content.showText(String.valueOf(booking.getNbr_rooms_reserved()));
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 16);
        content.newLineAtOffset(80, 500);
        content.showText("Total Amount : ");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 14);
        content.newLineAtOffset(250, 500);
        content.showText(String.valueOf(booking.getTotal_amount()));
        content.endText();
        //

        content.close();
        doc.save(selectedDir.getAbsolutePath() + "\\" + fileName);
        doc.close();

        return true;
    } catch (IOException ex) {
        Logger.getLogger(FXML_BookingListController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return false;
}

From source file:com.ing.connector.report.WReport.java

License:Open Source License

public boolean openReport() {
    try {/*from  w w  w. ja  v  a2  s  .com*/

        m_pdfReport = new PDDocument();
        openPage();

    } catch (Exception exc) {
        com.ing.connector.Registrar
                .logError(getClass().getName() + " failed to open " + getReportFileName() + " : " + exc);
        return false;
    }

    return true;
}

From source file:com.jaromin.alfresco.repo.content.transform.CorelDrawContentTransformer.java

License:Apache License

/**
 * //from w ww. j a  va2  s .  com
 * @param pageImages
 * @param out
 * @throws IOException
 * @throws FileNotFoundException
 * @throws COSVisitorException
 */
private void buildPdfFromImages(Map<File, Dimension> pageImages, OutputStream out)
        throws IOException, FileNotFoundException, COSVisitorException {
    PDDocument doc = new PDDocument();
    for (Map.Entry<File, Dimension> entry : pageImages.entrySet()) {
        File pFile = entry.getKey();
        Dimension d = entry.getValue();
        PDRectangle size = new PDRectangle(d.width, d.height);
        PDPage page = new PDPage(size);
        doc.addPage(page);

        PDXObjectImage ximage = new PDJpeg(doc, new FileInputStream(pFile));
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);
        contentStream.drawImage(ximage, size.getLowerLeftX(), size.getLowerLeftY());
        contentStream.close();
    }
    doc.save(out);
}