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

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

Introduction

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

Prototype

public void addPage(PDPage page) 

Source Link

Document

This will add a page to the document.

Usage

From source file:org.wso2.carbon.apimgt.impl.reportgen.ReportGenerator.java

License:Open Source License

/**
 * Generate PDF file for API microgateway request summary
 *
 * @param table object containing table headers and row data
 * @return InputStream pdf as a stream//from w w w  .j  a v a  2s  .c  o  m
 * @throws IOException
 * @throws COSVisitorException
 */
public InputStream generateMGRequestSummeryPDF(TableData table) throws IOException, COSVisitorException {

    String[] columnHeaders = table.getColumnHeaders();

    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    page.setMediaBox(PDPage.PAGE_SIZE_A4);
    page.setRotation(0);
    document.addPage(page);

    PDPageContentStream contentStream = new PDPageContentStream(document, page, false, false);

    // add logo
    InputStream in = APIManagerComponent.class.getResourceAsStream("/report/wso2-logo.jpg");
    PDJpeg img = new PDJpeg(document, in);
    contentStream.drawImage(img, 375, 755);

    // Add topic
    contentStream.setFont(PDType1Font.HELVETICA_BOLD, 16);
    writeContent(contentStream, CELL_MARGIN, 770, "API Microgateway request summary");

    // Add generated time
    contentStream.setFont(PDType1Font.HELVETICA_BOLD, FONT_SIZE);
    writeContent(contentStream, CELL_MARGIN, 730, "Report generated on: " + new Date().toString());

    contentStream.setFont(TEXT_FONT, FONT_SIZE);

    // add table with data
    drowTableGrid(contentStream, table.getRows().size());
    writeRowsContent(contentStream, columnHeaders, table.getRows());

    // Add meta data
    // Whenever the summary report structure is updated this should be changed
    String requestCount = table.getRows().get(0).getEntries().get(2);
    document.getDocumentInformation().setCustomMetadataValue(MGW_META, getMetaCount(requestCount));

    contentStream.close();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    document.save(out);
    document.close();

    return new ByteArrayInputStream(out.toByteArray());

}

From source file:patient_records_mng_sys.balamu.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

    String latta = "Lotta";
    System.out.println("Dagakara" + latta + " Balla");
    // String var="Testing";
    // jLabel1.setText("HelloMto! "+var+"");
    String bloody = "1227";
    try {//  w  w  w .  j  a  va  2s .co  m

        System.out.println("Create Simple PDF file with Text");
        String fileName = "patientReport.pdf"; // name of our file

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

        doc.addPage(page);

        PDPageContentStream content = new PDPageContentStream(doc, page);

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 20);
        content.moveTextPositionByAmount(220, 750);
        content.drawString("Patient Report Form");
        content.endText();

        int x = 80;
        int y = 700;
        String spac = "        ";
        String documen = "PatientID" + spac + "PatientName" + spac + "Clinic" + spac + "Diagnose";

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 16);
        content.moveTextPositionByAmount(x, 710);
        content.drawString(documen);
        content.endText();

        //To add from database//
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/itp?" + "user=root&password=sparksndl");
            Statement sqlState = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);
            String selectStuff = "Select `ID`,`patient_id`,`clinicName`,`diagnosis`,`dateOfEntry`,`allergiesIdentified`,`Remarks`,`nextClinicDate`,`ward` FROM `medical_records` WHERE `patient_id` LIKE "
                    + bloody + " ";
            rows = sqlState.executeQuery(selectStuff);
            Object[] tempRow;
            String[] records;
            while (rows.next()) {
                //tempRow=new Object[]{rows.getString(1),rows.getString(2),rows.getString(3),rows.getString(4),rows.getDate(5),rows.getString(6),rows.getString(7),rows.getString(8)};
                //dTableModel.addRow(tempRow);
                String id = rows.getString(1);
                String name = "Classified";
                String clinic = rows.getString(3);
                String diagnose = rows.getString(4);
                String aller = rows.getString(6);
                String remark = rows.getString(7);
                String space = "                 ";
                String document = id + space + space + space + name + space + space + clinic + space + diagnose;
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, 8);
                content.moveTextPositionByAmount(x, y);
                content.drawString(document);

                content.endText();
                y = y - 12;

            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }

        //Over//

        content.close();
        doc.save(fileName);
        doc.close();

        System.out.println("your file created in : " + System.getProperty("user.dir"));

    } catch (IOException | COSVisitorException e) {

        System.out.println(e.getMessage());

    }

    // TODO add your handling code here:
}

From source file:patient_records_mng_sys.send.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed

    String email1 = email.getText();

    String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";

    Boolean b = email1.matches(EMAIL_REGEX);

    if (b == true) {

        System.out.println("Correct Email");
        // String bloody=(String)search_key.getSelectedItem();
        //this.test();
        //Create the PDF Document//

        try {//from   w w w . ja v  a  2 s . co  m
            String key = (String) search_key.getSelectedItem();
            System.out.println("Creating PDF File");
            String fileName = "patientReport.pdf"; // name of our file

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

            doc.addPage(page);

            PDPageContentStream content = new PDPageContentStream(doc, page);

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 20);
            content.moveTextPositionByAmount(220, 750);
            content.drawString("Patient Report Form");
            content.endText();

            int x = 80;
            int y = 700;
            String spac = "        ";
            String documen = "PatientID" + spac + "PatientName" + spac + "Clinic" + spac + "Diagnose";

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 16);
            content.moveTextPositionByAmount(x, 710);
            content.drawString(documen);
            content.endText();

            //To add from database//
            // Connection conn=null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                ///conn = DriverManager.getConnection("jdbc:mysql://localhost/itp?"+"user=root&password=sparksndl");
                //conn = DriverManager.getConnection("jdbc:mysql://localhost/itp?"+"user="+user+"&password="+pass+"");
                Statement sqlState = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
                String selectStuff = "Select `ID`,`patient_id`,`clinicName`,`diagnosis`,`dateOfEntry`,`allergiesIdentified`,`Remarks`,`nextClinicDate`,`ward` FROM `medical_records` WHERE `patient_id` LIKE "
                        + key + " ";
                rows = sqlState.executeQuery(selectStuff);
                Object[] tempRow;
                String[] records;
                if (rows.next()) {
                    while (rows.next()) {
                        String id = rows.getString(1);
                        String name = "Classified";
                        String clinic = rows.getString(3);
                        String diagnose = rows.getString(4);
                        String aller = rows.getString(6);
                        String remark = rows.getString(7);
                        String space = "                 ";
                        String document = id + space + space + space + name + space + space + clinic + space
                                + diagnose;
                        content.beginText();
                        content.setFont(PDType1Font.HELVETICA, 8);
                        content.moveTextPositionByAmount(x, y);
                        content.drawString(document);

                        content.endText();
                        y = y - 12;
                    }
                } else {
                    JOptionPane.showMessageDialog(null,
                            "ID entry not available,Please register the patient or try again");
                }

            } catch (ClassNotFoundException | SQLException e) {
                System.out.println("Provide Correct Index");
                //e.printStackTrace();
            }

            //Document Creation Over//

            content.close();
            doc.save(fileName);
            doc.close();

            System.out.println("your report has been created in : " + System.getProperty("user.dir"));

        } catch (IOException | COSVisitorException e) {

            System.out.println(e.getMessage());

        }
        // String test="jsandunil@gmail.com";
        emailer mailme = new emailer();
        mailme.sendFromGMail(email1);

        //mailme.
        //Document Over//

    } else

        JOptionPane.showMessageDialog(null, "Incorrect Email Provided.", "Email Address Format",
                JOptionPane.ERROR_MESSAGE);

    // TODO add your handling code here:
}

From source file:PDF.PDFDateStampPartial.java

private void generatePDFFile(String pdfFileName, Boolean[][] statusArray, String date)
        throws IOException, COSVisitorException {
    PDDocument pdf = PDDocument.load(pdfFileName);
    List pages = pdf.getDocumentCatalog().getAllPages();
    Iterator<PDPage> iter = pages.iterator();
    int pageNum = 0; // 0 based
    //int sequenceNum = 1; // start from 0001
    PDDocument pdfBlank = new PDDocument();

    while (iter.hasNext()) {
        PDPage page = iter.next();/*from ww  w. jav  a 2  s. c  o m*/
        PDPage pageBlank = new PDPage();

        PDPageContentStream stream = new PDPageContentStream(pdf, page, true, false);
        PDPageContentStream streamBlank = new PDPageContentStream(pdfBlank, pageBlank, true, false);

        // == seq stamp
        if (statusArray[GlobalVar.SELECT_BUTTON_INDEX][pageNum]) {
            pageWrite(stream, date);
            pageWrite(streamBlank, date);
        }
        // == end of seq stamp
        pdfBlank.addPage(pageBlank);
        stream.close();
        streamBlank.close();

        pageNum++;
    }

    // out put two pdf files: one is template for printer print hardcopies, the other is digital copy
    String suffix = "_P dateStamped.pdf";
    pdfFileName = pdfFileName.replace(".pdf", suffix);
    String blankPdfFileName = pdfFileName.replace(".pdf", "BLANK.pdf");

    pdf.save(pdfFileName);
    pdfBlank.save(blankPdfFileName);

    pdf.close();
    pdfBlank.close();
}

From source file:PDF.PDFEditor.java

private void extractGoodBadPdf(PDDocument pdf, String auditPdfFileName, String rejectPdfFileName,
        Boolean[][] statusArray) throws COSVisitorException, IOException {
    PDDocument rejectPdf = new PDDocument();
    PDDocument auditPdf = new PDDocument();
    int pageNum = pdf.getNumberOfPages();

    // add reject page into rejectPdf
    for (int i = 0; i < pageNum; i++) {
        PDPage page = (PDPage) pdf.getDocumentCatalog().getAllPages().get(i);
        if (statusArray[GlobalVar.VOID_BUTTON_INDEX][i]) {
            rejectPdf.addPage(page);
        } else {// w  w  w  . j  a va 2  s.c  om
            auditPdf.addPage(page);
        }
    }

    rejectPdf.save(rejectPdfFileName);
    rejectPdf.close();

    auditPdf.save(auditPdfFileName);
    auditPdf.close();
}

From source file:PDF.PDFNumberingPartial.java

private void generatePDFFile(String pdfFileName, Boolean[][] statusArray, String cycle)
        throws IOException, COSVisitorException {
    PDDocument pdf = PDDocument.load(pdfFileName);
    List pages = pdf.getDocumentCatalog().getAllPages();
    Iterator<PDPage> iter = pages.iterator();

    PDDocument pdfBlank = new PDDocument();

    int pageNum = 0; // 0 based
    int sequenceNum = 1; // start from 0001
    while (iter.hasNext()) {
        PDPage page = iter.next();//w  ww.  j  a v a 2s . c  o  m
        PDPage pageBlank = new PDPage();

        PDPageContentStream stream = new PDPageContentStream(pdf, page, true, false);
        PDPageContentStream streamBlank = new PDPageContentStream(pdfBlank, pageBlank, true, false);

        if (statusArray[GlobalVar.SELECT_BUTTON_INDEX][pageNum]) {
            pageWrite(stream, sequenceNum, cycle);
            pageWrite(streamBlank, sequenceNum, cycle);
            sequenceNum++;
        }
        pdfBlank.addPage(pageBlank);

        stream.close();
        streamBlank.close();
        pageNum++;
    }

    // out put two pdf files: one is template for printer print hardcopies, the other is digital copy
    String suffix = "_" + cycle + "_P numbered.pdf";
    pdfFileName = pdfFileName.replace(".pdf", suffix);
    String blankPdfFileName = pdfFileName.replace(".pdf", "BLANK.pdf");

    pdf.save(pdfFileName);
    pdfBlank.save(blankPdfFileName);

    pdf.close();
    pdfBlank.close();
}

From source file:PDF.PDFRemover.java

private void extractGoodPdf(PDDocument pdf, String auditPdfFileName, Boolean[][] statusArray)
        throws COSVisitorException, IOException {

    PDDocument auditPdf = new PDDocument();
    int pageNum = pdf.getNumberOfPages();

    // add reject page into rejectPdf
    for (int i = 0; i < pageNum; i++) {
        PDPage page = (PDPage) pdf.getDocumentCatalog().getAllPages().get(i);
        if (!statusArray[GlobalVar.VOID_BUTTON_INDEX][i]) {

            auditPdf.addPage(page);
        }//from   w  w  w  . jav  a  2 s  .c o m
    }

    auditPdf.save(auditPdfFileName);
    auditPdf.close();
}

From source file:pdfbox.PDFA3File.java

License:Apache License

/**
 * Create a simple PDF/A-3 document.//  w w  w  .  j  ava2  s  .co m
 * This example is based on HelloWorld example.
 * As it is a simple case, to conform the PDF/A norm, are added : - the font
 * used in the document - the sRGB color profile - a light xmp block with only
 * PDF identification schema (the only mandatory) - an output intent To
 * conform to A/3 - the mandatory MarkInfo dictionary displays tagged PDF
 * support - and optional producer and - optional creator info is added
 * 
 * @param file
 *          The file to write the PDF to.
 * @param message
 *          The message to write in the file.
 * @throws Exception
 *           If something bad occurs
 */
public void doIt(String file, String message) throws Exception {
    // the document
    PDDocument doc = null;
    try {
        doc = new PDDocument();

        // now create the page and add content
        PDPage page = new PDPage();

        doc.addPage(page);

        InputStream fontStream = PDFA3File.class.getResourceAsStream("/Ubuntu-R.ttf");
        PDFont font = PDTrueTypeFont.loadTTF(doc, fontStream);

        // create a page with the message where needed
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, 700);
        contentStream.drawString(message);
        contentStream.endText();
        contentStream.saveGraphicsState();
        contentStream.close();

        PDDocumentCatalog cat = makeA3compliant(doc);

        InputStream colorProfile = PDFA3File.class.getResourceAsStream("/sRGB Color Space Profile.icm");

        // create output intent
        PDOutputIntent oi = new PDOutputIntent(doc, colorProfile);
        oi.setInfo("sRGB IEC61966-2.1");
        oi.setOutputCondition("sRGB IEC61966-2.1");
        oi.setOutputConditionIdentifier("sRGB IEC61966-2.1");
        oi.setRegistryName("http://www.color.org");
        cat.addOutputIntent(oi);

        doc.save(file);

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

From source file:pdfbox.PDFA3FileAttachment.java

License:Apache License

/**
 * Create a simple PDF/A-3 document./*  w  w  w .  j av a2 s  .c  o  m*/
 * This example is based on HelloWorld example.
 * As it is a simple case, to conform the PDF/A norm, are added : - the font
 * used in the document - the sRGB color profile - a light xmp block with only
 * PDF identification schema (the only mandatory) - an output intent To
 * conform to A/3 - the mandatory MarkInfo dictionary displays tagged PDF
 * support - and optional producer and - optional creator info is added
 * 
 * @param file
 *          The file to write the PDF to.
 * @param message
 *          The message to write in the file.
 * @throws Exception
 *           If something bad occurs
 */
public void doIt(String file, String message) throws Exception {
    // the document
    PDDocument doc = null;
    try {
        doc = new PDDocument();

        // now create the page and add content
        PDPage page = new PDPage();

        doc.addPage(page);

        InputStream fontStream = PDFA3FileAttachment.class.getResourceAsStream("/Ubuntu-R.ttf");
        PDFont font = PDTrueTypeFont.loadTTF(doc, fontStream);

        // create a page with the message where needed
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, 700);
        contentStream.drawString(message);
        contentStream.endText();
        contentStream.saveGraphicsState();
        contentStream.close();

        PDDocumentCatalog cat = makeA3compliant(doc);
        attachSampleFile(doc);

        InputStream colorProfile = PDFA3FileAttachment.class
                .getResourceAsStream("/sRGB Color Space Profile.icm");
        // create output intent
        PDOutputIntent oi = new PDOutputIntent(doc, colorProfile);
        oi.setInfo("sRGB IEC61966-2.1");
        oi.setOutputCondition("sRGB IEC61966-2.1");
        oi.setOutputConditionIdentifier("sRGB IEC61966-2.1");
        oi.setRegistryName("http://www.color.org");
        cat.addOutputIntent(oi);

        doc.save(file);

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

From source file:pdfbox.PDFAFile.java

License:Apache License

/**
 * Create a simple PDF/A document.//from ww  w.  j a  v a  2  s.c  om
 * This example is based on HelloWorld example.
 * As it is a simple case, to conform the PDF/A norm, are added : - the font
 * used in the document - a light xmp block with only PDF identification
 * schema (the only mandatory) - an output intent
 * 
 * @param file
 *          The file to write the PDF to.
 * @param message
 *          The message to write in the file.
 * @throws Exception
 *           If something bad occurs
 */
public void doIt(String file, String message) throws Exception {
    // the document
    PDDocument doc = null;
    try {
        doc = new PDDocument();

        PDPage page = new PDPage();
        doc.addPage(page);

        InputStream fontStream = PDFA3File.class.getResourceAsStream("/Ubuntu-R.ttf");
        PDFont font = PDTrueTypeFont.loadTTF(doc, fontStream);

        // create a page with the message where needed
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, 700);
        contentStream.drawString(message);
        contentStream.endText();
        contentStream.saveGraphicsState();
        contentStream.close();

        PDDocumentCatalog cat = doc.getDocumentCatalog();
        PDMetadata metadata = new PDMetadata(doc);
        cat.setMetadata(metadata);

        // jempbox version
        XMPMetadata xmp = new XMPMetadata();
        XMPSchemaPDFAId pdfaid = new XMPSchemaPDFAId(xmp);
        xmp.addSchema(pdfaid);
        pdfaid.setConformance("B");
        pdfaid.setPart(1);
        pdfaid.setAbout("");
        metadata.importXMPMetadata(xmp.asByteArray());

        InputStream colorProfile = PDFA3File.class.getResourceAsStream("/sRGB Color Space Profile.icm");
        // create output intent
        PDOutputIntent oi = new PDOutputIntent(doc, colorProfile);
        oi.setInfo("sRGB IEC61966-2.1");
        oi.setOutputCondition("sRGB IEC61966-2.1");
        oi.setOutputConditionIdentifier("sRGB IEC61966-2.1");
        oi.setRegistryName("http://www.color.org");
        cat.addOutputIntent(oi);

        doc.save(file);

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