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: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);//from   w w w  .j a va  2 s.c  om
        } else {
            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();//from  www. j av  a2s . co 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   ww  w  .j  av  a  2 s.c om
        }
    }

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

From source file:pdfbox.PDFA3File.java

License:Apache License

/**
 * Create a simple PDF/A-3 document./*from   ww w.  j av  a  2  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./*from ww w . j  ava 2  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 = 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./* ww  w. j  a v a 2s  .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 - 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();
        }
    }
}

From source file:pdfboxtest.PDFBoxTest.java

/**
 *//*from   w  w w . ja  v  a2  s .  c  om*/
public static void main(String[] args) throws Exception {

    GetFundamentals go = new GetFundamentals();
    // Create a document and add a page to it
    go.ticker = "AAN";
    String outputFileName = go.ticker + ".pdf";
    PDDocument document = new PDDocument();
    PDPage page1 = new PDPage(PDPage.PAGE_SIZE_LETTER);
    PDPage page2 = new PDPage(PDPage.PAGE_SIZE_LETTER);
    PDPage page3 = new PDPage(PDPage.PAGE_SIZE_LETTER);
    PDPage page4 = new PDPage(PDPage.PAGE_SIZE_LETTER);
    // PDPage.PAGE_SIZE_LETTER is also possible
    // rect can be used to get the page width and height
    document.addPage(page1);
    document.addPage(page2);
    document.addPage(page3);
    document.addPage(page4);

    // Create a new font object selecting one of the PDF base fonts
    PDFont fontPlain = PDType1Font.HELVETICA_BOLD;

    // Start a new content stream which will "hold" the to be created content
    PDPageContentStream cos = new PDPageContentStream(document, page1);

    // Define a text content stream using the selected font, move the cursor and draw some text
    setupDefault(cos, fontPlain, document, go);
    setupP1(cos, fontPlain, document, go.ticker);
    cos.close();
    cos = new PDPageContentStream(document, page2);
    setupDefault(cos, fontPlain, document, go);
    setupP2(cos, fontPlain, document);
    cos.close();
    cos = new PDPageContentStream(document, page3);
    setupDefault(cos, fontPlain, document, go);
    setupP3(cos, fontPlain, document);
    cos.close();
    cos = new PDPageContentStream(document, page4);
    setupDefault(cos, fontPlain, document, go);
    setupP4(cos, fontPlain, document);
    cos.close();

    // Make sure that the content stream is closed:

    // Save the results and ensure that the document is properly closed:
    document.save(outputFileName);
    document.close();
}

From source file:pdfsplicer.SplicerModel.java

License:Open Source License

/**
 * Create the new PDF, and save it./*from   w  w  w  .  ja  v a2 s  .com*/
 * 
 * @param saveFile the file to save it as
 * @throws IOException if it cannot save the file
 */
public void makeFinalizedPDF(File saveFile) throws IOException {

    PDDocument doc = null;
    PDDocument newdoc = new PDDocument();

    for (int i = 0; i < pageEntryPDFList.size(); ++i) {
        doc = pdfList.get(pageEntryPDFList.get(i));

        if (doc.isEncrypted()) {
            System.out.println("Error: Encrypted PDF");
            System.exit(1);
        }

        List<Integer> pRange = pageRangeList.get(i);
        PDFCloneUtility pdfCloner = new PDFCloneUtility(newdoc);
        for (int pNum : pRange) {
            PDPage page = doc.getPage(pNum - 1);
            COSDictionary clonedDict = (COSDictionary) pdfCloner.cloneForNewDocument(page);
            newdoc.addPage(new PDPage(clonedDict));
        }
    }

    newdoc.save(saveFile);
    if (newdoc != null) {
        newdoc.close();
    }
}

From source file:pl.vane.pdf.factory.PDFFactory.java

License:Open Source License

public static PDDocument create(PDFDocument pdf) throws IOException {

    log.trace("--- pdf start");
    PDDocument document = new PDDocument();

    log.trace("--- load fonts");

    Map<Integer, PDFont> fonts = loadFonts(pdf.getFont(), document);

    for (PDFPage data : pdf.getPage()) {
        // create page with size
        PDPage page = new PDPage();
        PDFPageSize size = data.getSize();
        PDRectangle mediaBox = new PDRectangle(size.getWidth(), size.getHeight());
        page.setMediaBox(mediaBox);//from w w w .  j av a 2s.c  o  m
        document.addPage(page);
        // create content
        PDPageContentStream stream = new PDPageContentStream(document, page);
        for (PDFContent content : data.getContent()) {
            if (content instanceof PDFTextContent) {
                PDFTextContent txt = (PDFTextContent) content;
                PDFont font = fonts.get(txt.getFontId());
                Point p = txt.getStart();
                PDFWriter.drawString(stream, font, txt.getFontSize(), txt.getLeading(), p.getX(), p.getY(),
                        txt.getText());
            }
        }
        stream.close();
    }

    log.trace("--- pdf end");

    return document;
}

From source file:pptxtopdf.TestPptxToPdf.java

public static void main(String[] args)
        throws FileNotFoundException, IOException, COSVisitorException, OpenXML4JException {
    // TODO code application logic here
    String filepath = "/home/sagar/Desktop/Shareback/test.pptx";
    FileInputStream is = new FileInputStream(filepath);
    XMLSlideShow pptx = new XMLSlideShow(is);
    Dimension pgsize = pptx.getPageSize();

    int idx = 1;/*  ww  w .  ja  v  a  2s .  c  o m*/
    for (XSLFSlide slide : pptx.getSlides()) {

        BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = img.createGraphics();
        // clear the drawing area
        graphics.setPaint(Color.white);
        graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));

        // render
        slide.draw(graphics);

        // save the output
        FileOutputStream out = new FileOutputStream("/home/sagar/Desktop/Shareback/img/slide-" + idx + ".jpg");
        javax.imageio.ImageIO.write(img, "jpg", out);
        out.close();

        idx++;
    }

    String someimg = "/home/sagar/Desktop/Shareback/pptx/img/";

    PDDocument document = new PDDocument();
    File file = new File(someimg);
    if (!file.exists())
        file.mkdir();

    if (file.isDirectory()) {
        for (File f : file.listFiles()) {

            InputStream in = new FileInputStream(f);

            BufferedImage bimg = ImageIO.read(in);
            float width = bimg.getWidth();
            float height = bimg.getHeight();
            PDPage page = new PDPage(new PDRectangle(width + 10, height + 10));
            document.addPage(page);
            PDXObjectImage img = new PDJpeg(document, new FileInputStream(f));
            PDPageContentStream contentStream = new PDPageContentStream(document, page);
            contentStream.drawImage(img, 0, 0);
            contentStream.close();
            in.close();
        }

        document.save("/home/sagar/Desktop/Shareback/test-generated-pptx.pdf");
        document.close();
    } else {
        System.out.println(someimg + "is not a Directory");
    }

}