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.olat.core.util.pdf.PdfDocument.java

License:Apache License

public PdfDocument(Locale locale) throws IOException {
    document = new PDDocument();
    printDate = Formatter.getInstance(locale).formatDate(new Date());
}

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.j  ava2  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  w w w  .  ja  v a  2  s .  c  o  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.pdfsam.pdfbox.component.PDDocumentHandler.java

License:Open Source License

/**
 * Creates a new handler with an empty underlying {@link PDDocument}.
 *///from   ww  w. j a  v  a  2 s .c  o m
public PDDocumentHandler() {
    this.document = new PDDocument();
    this.permissions = new PDDocumentAccessPermission(document);

}

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;//ww  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

public void convert(Collection<Page> pages, String targetPdf) {
    try {//ww  w .  j  a va 2 s.c  o m
        // Create a new empty document
        PDDocument document = new PDDocument();

        //Metadata (use first page)
        if (pages.size() > 0)
            addMetadata(document, pages.iterator().next());

        //Font
        createFont(document);

        //Add pages
        for (Iterator<Page> it = pages.iterator(); it.hasNext();)
            addPage(document, it.next());

        // Save the newly created document
        document.save(targetPdf);

        // finally make sure that the document is properly
        // closed.
        document.close();
    } catch (Exception exc) {
        exc.printStackTrace();
    }
}

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

License:Apache License

public void convert(Page page, String targetPdf) {
    try {// w w w .j  a v  a  2 s  . co m
        // Create a new empty document
        PDDocument document = new PDDocument();

        //Metadata
        addMetadata(document, page);

        //Font
        createFont(document);

        //Add page
        addPage(document, page);

        // Save the newly created document
        document.save(targetPdf);

        // finally make sure that the document is properly
        // closed.
        document.close();

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

From source file:org.qi4j.envisage.print.PDFWriter.java

License:Apache License

protected void writeImpl(File file, ApplicationDetailDescriptor descriptor, List<GraphDisplay> graphDisplays)
        throws IOException, COSVisitorException {
    try {//from w w  w. ja v  a  2 s .  c  o  m
        doc = new PDDocument();
        for (GraphDisplay graphDisplay : graphDisplays) {
            writeGraphPage(graphDisplay);
        }
        writePage(descriptor);
        if (curContentStream != null) {
            curContentStream.close();
            curContentStream = null;
        }
        doc.save(new FileOutputStream(file));
    } finally {
        if (curContentStream != null) {
            curContentStream.close();
            curContentStream = null;
        }

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

From source file:org.sejda.impl.pdfbox.component.PDDocumentHandler.java

License:Apache License

/**
 * Creates a new handler with an empty underlying {@link PDDocument}.
 * //from  www.  j  a  va2s  . c om
 * @throws TaskIOException
 */
public PDDocumentHandler() {
    this.document = new PDDocument();
    permissions = new PDDocumentAccessPermission(document);
}

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

License:Apache License

private void setPage() throws Exception {
    if (document == null) { //Initialize
        document = new PDDocument();
        page = new PDPage();
        page.setMediaBox(PDPage.PAGE_SIZE_A4);
        document.addPage(page);//from ww  w  .  j  a  va2 s. c  o m
        contentStream = new PDPageContentStream(document, page, false, false);
        contentStream.beginText();
        contentStream.moveTextPositionByAmount(xPos, yPos);
        isNewPage = true;
    } else {
        if (yPos <= 40) { //Close the old page create new
            contentStream.endText();
            contentStream.close();
            page = new PDPage();
            page.setMediaBox(PDPage.PAGE_SIZE_A4);
            document.addPage(page);
            contentStream = new PDPageContentStream(document, page, false, false);
            yPos = 800;
            xShift = 0;
            yShift = 0;
            contentStream.beginText();
            contentStream.setFont(font, font_size);
            contentStream.moveTextPositionByAmount(xPos, yPos);
            isNewPage = true;
        } else {
            contentStream.moveTextPositionByAmount(xShift, yShift);
        }
    }
}