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

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

Introduction

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

Prototype

public void save(OutputStream output) throws IOException 

Source Link

Document

This will save the document to an output stream.

Usage

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)
 *//*from  w  w  w  . ja  v  a  2  s .c om*/
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.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  w w .j a  v  a  2  s.  com
 * @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();
    }

}

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   w w  w  .j  ava 2s . com*/

    // 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.github.joemcintyre.pdffinish.PDFFinish.java

License:Open Source License

/**
 * Process the PDF input file, producing the output file.
 * /*from   ww w. j a  v  a  2 s .  co m*/
 * @param fileInput PDF input file.
 * @param fileOutput PDF output file.
 */
private void processPDF(File fileInput, File fileOutput) {
    PDDocument document = null;
    try {
        document = PDDocument.load(fileInput);
    } catch (IOException e) {
        System.out.println("Error reading PDF: " + e);
    }

    if (document != null) {
        boolean save = true;
        try {
            updateMetadata(document);
            if (fontList != null) {
                updateTOC(document);
            }
        } catch (IOException e) {
            System.out.println("Error processing PDF: " + e);
            save = false;
        }

        if (save) {
            try {
                document.save(fileOutput);
                System.out.println("Write complete");
            } catch (Exception e) {
                System.out.println("Error writing PDF: " + e);
            }
        }

        try {
            document.close();
        } catch (Exception e) {
            System.out.println("Error closing document: " + e);
        }
    }
}

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

License:Apache License

/**
 * Render this layout to an OutputStream.
 *
 * @param aCustomizer//from   w ww  .j a  v  a 2  s  .c om
 *        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  ww w . j a  va 2 s .  c om*/
        // 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.jaromin.alfresco.repo.content.transform.CorelDrawContentTransformer.java

License:Apache License

/**
 * // w  w w . jav  a  2  s  .co  m
 * @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);
}

From source file:com.jnd.sonar.analysisreport.AnalysisReportHelper.java

License:Open Source License

/**
* create the second sample document from the PDF file format specification.
* @param reportDataMap //from w  ww.ja v  a  2 s  .c  om
*
* @param file The file to write the PDF to.
* @param message The message to write in the file.
*
* @throws IOException If there is an error writing the data.
* @throws COSVisitorException If there is an error writing the PDF.
*/
public String createMetricReport(Map<String, String> reportDataMap) throws IOException, COSVisitorException {
    // the document
    PDDocument doc = null;
    StringBuilder strRow = new StringBuilder();

    String reportname = null;
    java.util.Random R = new java.util.Random();
    try {
        doc = new PDDocument();
        System.out.println("Creating PDF Line 264");
        PDPage page = new PDPage();
        doc.addPage(page);
        PDFont font = PDType1Font.HELVETICA_BOLD;

        PDPageContentStream contentStream = new PDPageContentStream(doc, page);

        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, 700 - 0);
        contentStream.drawString(" Sonar Analysis Report ");
        contentStream.endText();

        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, 700 - 20);
        contentStream.drawString("==================================================== ");
        contentStream.endText();

        System.out.println("Print Entries from Analysis Data Map.");
        int i = 2;
        for (Map.Entry<String, String> entry : reportDataMap.entrySet()) {
            contentStream.beginText();
            contentStream.setFont(font, 12);
            contentStream.moveTextPositionByAmount(100, 700 - (i * 20));
            contentStream.drawString(i + ") " + entry.getKey() + " = " + entry.getValue());
            contentStream.endText();

            //strRow.append(i + ") " + entry.getKey() + " = " + entry.getValue() + "\n ");
            i++;
        }
        //System.out.println(strRow);               

        contentStream.close();
        System.out.println("Done Writing Text.Save Doc.");

        reportname = "sonarreport" + java.util.Calendar.getInstance().getTimeInMillis() + "_" + R.nextInt()
                + ".pdf";
        doc.save(reportname);
        System.out.println("Report Created.Exit to email sending. name=>" + reportname);
    } finally {
        if (doc != null) {
            doc.close();
        }
    }
    return reportname;
}

From source file:com.jt.tool.pdf.CreateBookmarks.java

License:Apache License

public static void createBookmark(String srcFile, String targetFile, String reg) throws Exception {
    PDDocument document = null;
    try {//from ww  w. j  a  v a  2 s. c  o m
        document = PDDocument.load(new File(srcFile));
        if (document.isEncrypted()) {
            System.err.println("Error: Cannot add bookmarks to encrypted document.");
            System.exit(1);
        }
        PDDocumentOutline outline = new PDDocumentOutline();
        document.getDocumentCatalog().setDocumentOutline(outline);
        PDOutlineItem pagesOutline = new PDOutlineItem();
        pagesOutline.setTitle("All Pages");
        //            outline.appendChild(pagesOutline);
        List pages = new ArrayList();
        //                    document.getDocumentCatalog().getAllPages();
        for (int i = 12; i < pages.size(); i++) {
            String pageText = getPageText(document, i + 1, 0);
            String[] strings = matchTitle(pageText, reg);
            if (makeBookmark(strings)) {
                PDPage page = (PDPage) pages.get(i);
                PDPageFitWidthDestination dest = new PDPageFitWidthDestination();
                dest.setPage(page);
                PDOutlineItem bookmark = new PDOutlineItem();
                bookmark.setDestination(dest);
                bookmark.setTitle(strings[0]);
                //                    pagesOutline.appendChild(bookmark);
                System.out.println("add " + strings[0]);
            }
        }
        pagesOutline.openNode();
        outline.openNode();
        document.save(targetFile);
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

From source file:com.mirth.connect.connectors.doc.DocumentDispatcher.java

License:Open Source License

private void encryptPDF(InputStream inputStream, OutputStream outputStream, String password) throws Exception {
    PDDocument document = null;

    try {//w w w  .  j  a  v  a  2  s  .c o  m
        document = PDDocument.load(inputStream);

        AccessPermission accessPermission = new AccessPermission();
        accessPermission.setCanAssembleDocument(false);
        accessPermission.setCanExtractContent(true);
        accessPermission.setCanExtractForAccessibility(false);
        accessPermission.setCanFillInForm(false);
        accessPermission.setCanModify(false);
        accessPermission.setCanModifyAnnotations(false);
        accessPermission.setCanPrint(true);
        accessPermission.setCanPrintDegraded(true);

        String ownerPassword = System.currentTimeMillis() + "+" + Runtime.getRuntime().freeMemory() + "+"
                + (ownerPasswordSeq++);
        StandardProtectionPolicy policy = new StandardProtectionPolicy(ownerPassword, password,
                accessPermission);
        policy.setEncryptionKeyLength(128);
        document.protect(policy);

        document.save(outputStream);
    } catch (Exception e) {
        throw e;
    } finally {
        if (document != null) {
            document.close();
        }
    }
}