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.ghost4j.document.PDFDocument.java

License:LGPL

public Document extract(int begin, int end) throws DocumentException {

    this.assertValidPageRange(begin, end);

    PDFDocument result = new PDFDocument();

    ByteArrayInputStream bais = null;
    ByteArrayOutputStream baos = null;

    if (content != null) {

        PDDocument document = new PDDocument();

        try {//ww w  .  ja  v  a 2  s  .  c o  m

            bais = new ByteArrayInputStream(content);
            baos = new ByteArrayOutputStream();
            PDDocument inputPDF = PDDocument.load(bais);
            while (begin <= end) {
                document.addPage((PDPage) inputPDF.getDocumentCatalog().getAllPages().get(begin - 1));
                begin++;
            }
            document.save(baos);
            document.close();
            result.load(new ByteArrayInputStream(baos.toByteArray()));

        } catch (Exception e) {
            throw new DocumentException(e);
        } finally {
            IOUtils.closeQuietly(bais);
            IOUtils.closeQuietly(baos);
        }

    }

    return result;
}

From source file:org.ghost4j.document.PDFDocument.java

License:LGPL

@Override
public void append(Document document) throws DocumentException {

    super.append(document);

    ByteArrayOutputStream baos = null;
    PDDocument mergedDocument = new PDDocument();

    try {//from  w  w  w.j a  va2 s.  co  m

        baos = new ByteArrayOutputStream();
        ByteArrayInputStream bais = new ByteArrayInputStream(content);
        PDDocument pDocument = PDDocument.load(bais);
        int pageCount = pDocument.getNumberOfPages();
        for (int i = 0; i < pageCount; i++) {
            mergedDocument.addPage((PDPage) pDocument.getDocumentCatalog().getAllPages().get(i));
        }

        // copy new document
        ByteArrayInputStream baisNewDoc = new ByteArrayInputStream(document.getContent());
        PDDocument pNewDocument = PDDocument.load(baisNewDoc);
        pageCount = pNewDocument.getNumberOfPages();
        for (int i = 0; i < pageCount; i++) {
            mergedDocument.addPage((PDPage) pNewDocument.getDocumentCatalog().getAllPages().get(i));
        }
        mergedDocument.save(baos);
        mergedDocument.close();
        // replace content with new content
        content = baos.toByteArray();

    } catch (Exception e) {
        throw new DocumentException(e);
    } finally {
        IOUtils.closeQuietly(baos);
    }

}

From source file:org.kay.ini.ExportPDF.java

public void createPDF(ArrayList<Connection> exportList) {

    PDFont font = PDType1Font.HELVETICA_BOLD;

    try {/* www.  jav  a  2s . c om*/

        PDDocument document = new PDDocument();

        PDPage page = new PDPage();

        document.addPage(page);

        PDPageContentStream content = new PDPageContentStream(document, page, true, true);
        content.beginText();
        content.setFont(font, 12);

        content.moveTextPositionByAmount(100, 700);
        for (Connection con : exportList) {
            content.drawString(con.getKey() + " = " + con.getValue());
            content.moveTextPositionByAmount(0, -15);
        }

        content.endText();
        content.close();

        document.save(saveTo);
        JOptionPane.showMessageDialog(null, "success");

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.getMessage());

    }

}

From source file:org.kuali.coeus.common.impl.person.signature.PersonSignatureServiceImpl.java

License:Open Source License

/**
 * This method is to scan for signature tag in each page and apply the signature
 * at desired location./*from w  w  w . j  a va2s . c  o m*/
 * @param imageData
 * @param originalByteArrayOutputStream
 */
@SuppressWarnings("unchecked")
protected ByteArrayOutputStream scanAndApplyAutographInEachPage(byte[] imageData,
        ByteArrayOutputStream originalByteArrayOutputStream) throws Exception {
    ByteArrayOutputStream outputStream = originalByteArrayOutputStream;
    byte[] pdfFileData = originalByteArrayOutputStream.toByteArray();
    PDDocument originalDocument = getPdfDocument(pdfFileData); //PDDocument.load(is);
    PDDocument signatureDocument = new PDDocument();
    List<PDPage> originalDocumentPages = originalDocument.getDocumentCatalog().getAllPages();
    for (PDPage page : originalDocumentPages) {
        List<String> signatureTags = new ArrayList<String>(getSignatureTagParameter());
        PersonSignatureLocationHelper printer = new PersonSignatureLocationHelper(signatureTags);
        PDStream contents = page.getContents();
        if (contents != null) {
            printer.processStream(page, page.findResources(), page.getContents().getStream());
        }
        PDPage signaturePage = new PDPage();
        if (printer.isSignatureTagExists()) {
            PDJpeg signatureImage = new PDJpeg(signatureDocument, getBufferedImage(imageData));
            PDPageContentStream stream = new PDPageContentStream(signatureDocument, signaturePage, true, true);
            for (PersonSignaturePrintHelper signatureHelper : printer.getPersonSignatureLocations()) {
                float coordinateX = signatureHelper.getCoordinateX();
                float coordinateY = signatureHelper.getCoordinateY() - signatureImage.getHeight()
                        - ADDITIONAL_SPACE_BETWEEN_TAG_AND_IMAGE;
                stream.drawImage(signatureImage, coordinateX, coordinateY);
                stream.close();
            }
        } else {
            signaturePage = page;
        }
        signatureDocument.addPage(signaturePage);
    }

    Overlay overlay = new Overlay();
    overlay.overlay(signatureDocument, originalDocument);

    originalDocument.save(outputStream);
    originalDocument.close();
    signatureDocument.close();
    return outputStream;
}

From source file:org.nuxeo.typeDocPkg.TestPdfBoxN.java

License:Apache License

public void create(String message, String outfile) throws IOException, COSVisitorException {
    PDDocument doc = null;
    try {//from w  ww.  j av  a  2s  .  co  m
        doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);
        PDFont font = PDType1Font.HELVETICA;
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, 700);
        contentStream.drawString(message);
        contentStream.endText();
        contentStream.close();
        doc.save(outfile);
        doc.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.oscarehr.document.web.SplitDocumentAction.java

License:Open Source License

public ActionForward split(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String docNum = request.getParameter("document");
    String[] commands = request.getParameterValues("page[]");

    Document doc = documentDAO.getDocument(docNum);

    //      String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
    //      new File(docdownload);
    String docdownload = EDocUtil.getDocumentDir(doc.getDocfilename());

    String newFilename = doc.getDocfilename();
    String dbPrefix = EDocUtil.getDocumentPrefix(doc.getDocfilename());

    //      FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename());
    FileInputStream input = new FileInputStream(EDocUtil.getDocumentPath(newFilename));
    PDFParser parser = new PDFParser(input);
    parser.parse();//from ww w . ja  va  2  s.  c o  m
    PDDocument pdf = parser.getPDDocument();

    PDDocument newPdf = new PDDocument();

    List pages = pdf.getDocumentCatalog().getAllPages();

    if (commands != null) {
        for (String c : commands) {
            String[] command = c.split(",");
            int pageNum = Integer.parseInt(command[0]);
            int rotation = Integer.parseInt(command[1]);

            PDPage p = (PDPage) pages.get(pageNum - 1);
            p.setRotation(rotation);

            newPdf.addPage(p);
        }

    }

    //newPdf.save(docdownload + newFilename);

    if (newPdf.getNumberOfPages() > 0) {
        LoggedInInfo loggedInInfo = LoggedInInfo.loggedInInfo.get();

        //         EDoc newDoc = new EDoc("","", newFilename, "", loggedInInfo.loggedInProvider.getProviderNo(), doc.getDoccreator(), "", 'A', oscar.util.UtilDateUtilities.getToday("yyyy-MM-dd"), "", "", "demographic", "-1",0);
        EDoc newDoc = new EDoc("", "", EDocUtil.getDocumentFileName(newFilename), "",
                loggedInInfo.loggedInProvider.getProviderNo(), doc.getDoccreator(), "", 'A',
                oscar.util.UtilDateUtilities.getToday("yyyy-MM-dd"), "", "", "demographic", "-1", 0);
        newDoc.setFileName(dbPrefix + '.' + newDoc.getFileName());
        newDoc.setDocPublic("0");
        newDoc.setContentType("application/pdf");
        newDoc.setNumberOfPages(newPdf.getNumberOfPages());

        String newDocNo = EDocUtil.addDocumentSQL(newDoc);

        //         //newPdf.save(docdownload + newDoc.getFileName());
        System.gc(); //avoid Windows lock on channel
        newPdf.save(docdownload + EDocUtil.getDocumentFileName(newDoc.getFileName()));
        newPdf.close();

        WebApplicationContext ctx = WebApplicationContextUtils
                .getRequiredWebApplicationContext(request.getSession().getServletContext());
        ProviderInboxRoutingDao providerInboxRoutingDao = (ProviderInboxRoutingDao) ctx
                .getBean("providerInboxRoutingDAO");
        providerInboxRoutingDao.addToProviderInbox("0", newDocNo, "DOC");

        List<ProviderInboxItem> routeList = providerInboxRoutingDao.getProvidersWithRoutingForDocument("DOC",
                docNum);
        for (ProviderInboxItem i : routeList) {
            providerInboxRoutingDao.addToProviderInbox(i.getProviderNo(), newDocNo, "DOC");
        }

        providerInboxRoutingDao.addToProviderInbox(loggedInInfo.loggedInProvider.getProviderNo(), newDocNo,
                "DOC");

        QueueDocumentLinkDao queueDocumentLinkDAO = (QueueDocumentLinkDao) ctx.getBean("queueDocumentLinkDAO");
        Integer qid = 1;
        Integer did = Integer.parseInt(newDocNo.trim());
        queueDocumentLinkDAO.addToQueueDocumentLink(qid, did);

        ProviderLabRoutingDao providerLabRoutingDao = (ProviderLabRoutingDao) SpringUtils
                .getBean("providerLabRoutingDao");

        List<ProviderLabRoutingModel> result = providerLabRoutingDao.getProviderLabRoutingDocuments(docNum);
        if (!result.isEmpty()) {
            new ProviderLabRouting().route(newDocNo, result.get(0).getProviderNo(), "DOC");
        }

        PatientLabRoutingDao patientLabRoutingDao = (PatientLabRoutingDao) SpringUtils
                .getBean("patientLabRoutingDao");
        List<PatientLabRouting> result2 = patientLabRoutingDao.findDocByDemographic(docNum);

        if (!result2.isEmpty()) {
            PatientLabRouting newPatientRoute = new PatientLabRouting();

            newPatientRoute.setDemographicNo(result2.get(0).getDemographicNo());
            newPatientRoute.setLabNo(Integer.parseInt(newDocNo));
            newPatientRoute.setLabType("DOC");

            patientLabRoutingDao.persist(newPatientRoute);
        }

        DocumentDAO documentDao = (DocumentDAO) SpringUtils.getBean("documentDAO");
        CtlDocument result3 = documentDao.getCtrlDocument(Integer.parseInt(docNum));

        if (result3 != null) {
            CtlDocumentPK ctlDocumentPK = new CtlDocumentPK(Integer.parseInt(newDocNo), "demographic");
            CtlDocument newCtlDocument = new CtlDocument(ctlDocumentPK, result3.getModuleId());
            newCtlDocument.setStatus(result3.getStatus());
            documentDao.saveCtlDocument(newCtlDocument);
        }

    }

    pdf.close();
    input.close();

    return mapping.findForward("success");
}

From source file:org.pdfgal.pdfgal.pdfgal.impl.PDFGalImpl.java

License:Open Source License

@Override
public List<String> split(final String inputUri, final String outputUri, final List<Integer> pages)
        throws IOException, COSVisitorException {

    final List<String> result = new ArrayList<String>();

    if (StringUtils.isNotBlank(inputUri) && StringUtils.isNotBlank(outputUri)
            && CollectionUtils.isNotEmpty(pages)) {

        final PDDocument doc = PDDocument.load(inputUri);
        final List<PDDocument> splittedDocs = new ArrayList<PDDocument>();
        @SuppressWarnings("unchecked")
        final List<PDPage> pagesList = doc.getDocumentCatalog().getAllPages();

        // This section creates a new document for each split
        // indicated into the list, except the last one.
        Integer currentPage = 0;/*from ww  w .  ja v  a  2 s  . co m*/
        for (final Integer page : pages) {
            final PDDocument document = new PDDocument();
            for (Integer i = currentPage; i <= page - 2; i++) {
                document.addPage(pagesList.get(i));
            }
            splittedDocs.add(document);
            currentPage = page - 1;
            document.close();
        }

        // This section splits the last document
        final PDDocument lastDocument = new PDDocument();
        for (Integer i = currentPage; i < pagesList.size(); i++) {
            lastDocument.addPage(pagesList.get(i));
        }
        splittedDocs.add(lastDocument);
        lastDocument.close();

        Integer subIndex = 1;
        for (final PDDocument document : splittedDocs) {
            final String extension = this.converterUtils.addSubIndexBeforeExtension(outputUri, subIndex++);
            document.save(extension);
            result.add(extension);
        }

        doc.close();

    } else {
        throw new IllegalArgumentException(Constants.ILLEGAL_ARGUMENT_EXCEPTION_MESSAGE);
    }

    return result;
}

From source file:org.pensco.CreateStatementsOp.java

License:Open Source License

protected Blob buildPDF(String inCustomer, Calendar inStart, Calendar inEnd)
        throws IOException, COSVisitorException {

    Blob result = null;/*from w w  w . j a  va 2  s .  co m*/

    PDDocument pdfDoc = new PDDocument();
    PDPage page = new PDPage();
    pdfDoc.addPage(page);
    PDRectangle rect = page.getMediaBox();
    float rectH = rect.getHeight();

    PDFont font = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;
    PDFont fontOblique = PDType1Font.HELVETICA_OBLIQUE;
    PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page);

    int line = 0;

    contentStream.beginText();
    contentStream.setFont(fontOblique, 10);
    contentStream.moveTextPositionByAmount(230, 20);
    contentStream.drawString("(Statement randomly generated)");
    contentStream.endText();

    line += 3;
    contentStream.beginText();
    contentStream.setFont(fontBold, 12);
    contentStream.moveTextPositionByAmount(300, rectH - 20 * (++line));
    contentStream.drawString(inCustomer);
    contentStream.endText();

    contentStream.beginText();
    contentStream.setFont(fontBold, 12);
    contentStream.moveTextPositionByAmount(300, rectH - 20 * (++line));
    contentStream.drawString(
            "Statement from " + yyyyMMdd.format(inStart.getTime()) + " to " + yyyyMMdd.format(inEnd.getTime()));
    contentStream.endText();

    line += 3;
    statementLines = ToolsMisc.randomInt(3, 9);
    boolean isDebit = false;
    for (int i = 1; i <= statementLines; ++i) {
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, rectH - 20 * line);
        contentStream.drawString("" + i);
        contentStream.endText();

        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(120, rectH - 20 * line);
        isDebit = ToolsMisc.randomInt(0, 10) > 7;
        if (isDebit) {
            contentStream.drawString("Withdraw Funds to account " + MiscUtils.getSomeUID(6));
        } else {
            contentStream.drawString("Add Funds to account " + MiscUtils.getSomeUID(6));
        }
        contentStream.endText();

        contentStream.beginText();
        if (isDebit) {
            contentStream.setFont(fontOblique, 12);
            contentStream.moveTextPositionByAmount(350, rectH - 20 * line);
        } else {
            contentStream.setFont(font, 12);
            contentStream.moveTextPositionByAmount(450, rectH - 20 * line);
        }
        contentStream.drawString("" + ToolsMisc.randomInt(1000, 9000) + "." + ToolsMisc.randomInt(10, 90));
        contentStream.endText();

        line += 1;
    }
    contentStream.close();
    contentStream = null;

    if (logoImage != null) {
        PDXObjectImage ximage = new PDPixelMap(pdfDoc, logoImage);

        contentStream = new PDPageContentStream(pdfDoc, page, true, true);
        contentStream.endMarkedContentSequence();
        contentStream.drawXObject(ximage, 10, rectH - 20 - ximage.getHeight(), ximage.getWidth(),
                ximage.getHeight());
        contentStream.close();
        contentStream = null;
    }

    result = MiscUtils.saveInTempFile(pdfDoc);
    pdfDoc.close();

    return result;

}

From source file:org.primaresearch.pdf.PageToPdfConverterUsingPdfBox.java

License:Apache License

private void addPage(PDDocument doc, Page page) {
    try {/*from www .j a v  a  2  s  .com*/
        // Create a new blank page and add it to the document

        //TODO Use image DPI and size
        //The measurement unit of the PDF is point (1 Point = 0.0352777778 cm)
        //For now: Set the PDF size to the PAGE size (1px = 1pt)
        //PDPage pdfPage = new PDPage(PDPage.PAGE_SIZE_A4); 
        PDPage pdfPage = new PDPage(new PDRectangle(page.getLayout().getWidth(), page.getLayout().getHeight()));
        doc.addPage(pdfPage);

        if (DEBUG) {
            System.out.println("Mediabox width: " + pdfPage.getMediaBox().getWidth());
            System.out.println("Mediabox height: " + pdfPage.getMediaBox().getHeight());
        }

        // Start a new content stream which will "hold" the to be created content
        PDPageContentStream contentStream = new PDPageContentStream(doc, pdfPage);

        try {
            addText(contentStream, page);
            // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
            //contentStream.beginText();
            //contentStream.setFont( font, 12 );
            //contentStream.moveTextPositionByAmount( 100, 700 );
            //contentStream.drawString( "Hello World" );
            //contentStream.endText();
        } finally {
            // Make sure that the content stream is closed:
            contentStream.close();
        }
    } catch (Exception exc) {
        exc.printStackTrace();
    }

}

From source file:org.socialbiz.cog.util.PDFUtil.java

License:Apache License

public static void main(String[] args) { //For test
    try {/* w w w  .ja  v  a  2  s  .com*/
        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();
    }
}