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:org.socialbiz.cog.util.PDFUtil.java

License:Apache License

public static void main(String[] args) { //For test
    try {/*from w  w w. j  a  va2 s. c  om*/
        String path = args[0];
        PDDocument document = new PDDocument();
        PDPage page = new PDPage();
        page.setMediaBox(PDPage.PAGE_SIZE_A4);
        document.addPage(page);
        PDFont font = PDType1Font.HELVETICA;

        PDPageContentStream contentStream = new PDPageContentStream(document, page, false, false);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, 800);
        String x = "hello world";
        contentStream.drawString(x);
        contentStream.moveTextPositionByAmount(-90, -15);
        contentStream.setFont(font, 12);
        contentStream.drawString("Hello World3");
        contentStream.endText();
        contentStream.close();
        document.save(path);
        document.close();
        System.out.println("DONE..");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.socialbiz.cog.WikiToPDF.java

License:Apache License

public void writeWikiAsPDF(NGPage ngp, Vector<NoteRecord> publicNoteList, Vector<NoteRecord> memberNoteList)
        throws Exception {

    if (publicNoteList == null) {
        throw new Exception("The publicNoteList parameter must not be null.  Send an empty collection instead");
    }/* w ww .  j a  v  a  2  s . c om*/
    if (memberNoteList == null) {
        throw new Exception("The memberNoteList parameter must not be null.  Send an empty collection instead");
    }

    int totalNotes = publicNoteList.size() + memberNoteList.size();
    pddoc = new PDDocument();

    if (totalNotes > 1) {
        writeTOCPage(ngp, publicNoteList, memberNoteList);
    }

    int noteCount = 0;
    if (publicNoteList.size() > 0) {
        for (NoteRecord lr : publicNoteList) {
            noteCount++;
            writeNoteToPDF(ngp, lr, noteCount);
        }
    }

    if (memberNoteList.size() > 0) {
        for (NoteRecord lr : memberNoteList) {
            noteCount++;
            writeNoteToPDF(ngp, lr, noteCount);
        }
    }

    endPage();

    String fileName = ngp.getKey() + ".pdf";
    ar.resp.setContentType("application/pdf");
    ar.resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    OutputStream out = ar.resp.getOutputStream();
    pddoc.save(out);
    pddoc.close();
    out.flush();
}

From source file:org.wso2.carbon.apimgt.impl.indexing.indexer.PDFIndexerTest.java

License:Open Source License

@Test
public void testShouldReturnIndexedDocumentWhenParameterCorrect() throws IOException {
    String mediaType = "application/pdf+test";
    final String MEDIA_TYPE = "mediaType";
    PDFParser parser = Mockito.mock(PDFParser.class);
    COSDocument cosDoc = Mockito.mock(COSDocument.class);
    PDFTextStripper pdfTextStripper = Mockito.mock(PDFTextStripper.class);
    Mockito.doThrow(IOException.class).when(cosDoc).close();
    Mockito.when(parser.getDocument()).thenReturn(new COSDocument()).thenReturn(cosDoc);
    Mockito.when(pdfTextStripper.getText(new PDDocument())).thenReturn("");
    PDFIndexer pdfIndexer = new PDFIndexerWrapper(parser, pdfTextStripper);

    // should return the default media type when media type is not defined in file2Index
    IndexDocument pdf = pdfIndexer.getIndexedDocument(file2Index);
    if (!"application/pdf".equals(pdf.getFields().get(MEDIA_TYPE).get(0))) {
        Assert.fail();/*  w ww. jav  a 2s. c  o m*/
    }

    // should return the media type we have set in the file2Index even if error occurs in finally block
    file2Index.mediaType = mediaType;
    pdf = pdfIndexer.getIndexedDocument(file2Index);
    if (!mediaType.equals(pdf.getFields().get(MEDIA_TYPE).get(0))) {
        Assert.fail();
    }

}

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/*ww w  .j  a v  a2  s  . c om*/
 * @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:org.zaproxy.zap.extension.alertReport.AlertReportExportPDF.java

License:Apache License

/**
 * export the alerts to the named file, using the options specified
 *
 * @param alerts/*  w w  w.j  a  v a2s . c  o m*/
 * @param fileName
 * @param extensionExport
 * @return
 */
public boolean exportAlert(java.util.List<java.util.List<Alert>> alerts, String fileName,
        ExtensionAlertReportExport extensionExport) {
    document = new PDDocument();
    File outputfile = new File(fileName);
    try {
        // add the PDF metadata and title page in code
        addMetaData(extensionExport);
        addTitlePage(extensionExport);

        // add the alert content for each of the alert categories in turn
        for (int i = 0; i < alerts.size(); i++) {
            java.util.List<Alert> alertAux = alerts.get(i);
            addContent(alertAux, extensionExport);
        }
        // and tidy up afterwards
        document.save(outputfile);
        document.close();
        return true;

    } catch (Exception e) {
        logger.error("An error occurred trying to generate a Report PDF: " + e);
        return false;
    }
}

From source file:paper2ebook.Transformer.java

License:Apache License

/**
 * Output a PDF with as many pages as there are interesting areas in the
 * input document//from w  w w.  j ava 2s .com
 */
@Override
public PDDocument extract() throws IOException {
    PDDocument extractedDocument = new PDDocument();
    extractedDocument.setDocumentInformation(sourceDocument.getDocumentInformation());
    extractedDocument.getDocumentCatalog()
            .setViewerPreferences(sourceDocument.getDocumentCatalog().getViewerPreferences());

    @SuppressWarnings("unchecked")
    List<PDPage> pages = sourceDocument.getDocumentCatalog().getAllPages();
    int pageCounter = 1;
    for (PDPage page : pages) {
        if (pageCounter >= startPage && pageCounter <= endPage) {

            List<PDRectangle> zoomedFragments = getFragments(page);
            for (PDRectangle fragment : zoomedFragments) {
                PDPage outputPage = extractedDocument.importPage(page);
                outputPage.setCropBox(fragment);
                outputPage.setMediaBox(page.getMediaBox());
                outputPage.setResources(page.findResources());
                outputPage.setRotation(page.findRotation());

                // TODO: rotate the page in landscape mode is width > height
            }
        }
        pageCounter++;
    }
    return extractedDocument;
}

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 {/*from   www  .  ja v  a 2  s  .c  o 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 {/* w  ww  .  j a va 2s  . c  o 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  .  j a  v a2  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

public void generatePDFFile(String date, String pdfFileName, Boolean[][] statusArray, String cycle)
        throws IOException, COSVisitorException {
    PDDocument pdf = PDDocument.load(pdfFileName);
    PDDocument blanPdf = new PDDocument();

    List pages = pdf.getDocumentCatalog().getAllPages();
    Iterator<PDPage> iter = pages.iterator();
    int pageNum = 0; // 0 based
    int sequenceNum = 1; // start from 0001
    while (iter.hasNext()) {
        PDPage page = iter.next();/*w w  w . j  a  va2s  .  co  m*/
        PDPageContentStream stream = new PDPageContentStream(pdf, page, true, false);

        // == date stamp
        stream.beginText();
        stream.setFont(PDType1Font.HELVETICA, 20);
        stream.moveTextPositionByAmount(200, 20);
        stream.drawString(date); //date stamp 
        stream.endText();
        // == end of date stamp

        //             // == void stamp
        //            if (statusArray[GlobalVar.VOID_BUTTON_INDEX][pageNum]) {
        //                stream.drawImage(voidMark, 0, 0);
        //            }
        // == end of void stamp

        // == seq stamp
        if (statusArray[GlobalVar.SELECT_BUTTON_INDEX][pageNum]) {
            stream.beginText();
            stream.setFont(PDType1Font.HELVETICA, 24);
            stream.moveTextPositionByAmount(600, 400);
            stream.setTextRotation(3.14 / 2, 600, 400); // rotate text 90 degree at x = 600, y = 400

            stream.drawString(cycle + "/" + GlobalVar.globalCountGenerator5Digit(sequenceNum));
            sequenceNum++;
            stream.endText();
        }
        // == end of seq stamp

        stream.close();
        pageNum++;
    }
    // out put two pdf files: one for audit, the other for reject
    String rejectPdfFileName = pdfFileName.replace(".pdf", "_forReject.pdf");
    String auditPdfFileName = pdfFileName.replace(".pdf", "_forAudit.pdf");
    extractGoodBadPdf(pdf, auditPdfFileName, rejectPdfFileName, statusArray);

    pdf.close();
}