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

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

Introduction

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

Prototype

public static PDDocument load(byte[] input) throws IOException 

Source Link

Document

Parses a PDF.

Usage

From source file:ambroafb.general.PDFHelper.java

public PDFHelper(InputStream in) throws IOException {
    doc = PDDocument.load(in);
    rend = new PDFRenderer(doc);
}

From source file:app.Instance.java

/**
 * Ajoute un fichier dj existant//from   w  w w  .j  a v a  2s. c o m
 *
 * @param file
 * @return
 * @throws IOException
 */
public static DocFile addFile(File file) throws IOException {
    DocFile docFile = null;
    PDDocument document = null;
    try {
        if (file.exists()) {
            if (!isAlreadyOpened(file)) {
                document = PDDocument.load(file);
                if (document != null) {
                    docFile = new DocFile(docFiles.size(), document, file);
                } else {
                    System.out.println("Le document est null");
                }
            } else {
                docFile = getDocFileByFile(file);
                System.out.println("Le fichier est dj ouvert");
            }
            opened = docFile.getId();
            docFiles.add(docFile);
            docFile.setSaved(true);
            saveInSaveFile(file, TRANSLATOR.getString("APP_NAME") + "_recent");
        } else {
            System.out.println("Le fichier n'existe pas");
        }
    } finally {
        if (document != null) {
            //document.close();
        }
    }
    return docFile;
}

From source file:architecture.ee.web.attachment.DefaultAttachmentManager.java

License:Apache License

protected File getThumbnailFromCacheIfExist(Attachment attach, int width, int height) throws IOException {

    log.debug("thumbnail generation " + width + "x" + height);
    File dir = getAttachmentCacheDir();
    File file = new File(dir, toThumbnailFilename(attach, width, height));
    File originalFile = getAttachmentFromCacheIfExist(attach);
    log.debug("source: " + originalFile.getAbsoluteFile() + ", " + originalFile.length());
    log.debug("thumbnail:" + file.getAbsoluteFile());

    if (file.exists() && file.length() > 0) {
        attach.setThumbnailSize((int) file.length());
        return file;
    }/*from   w  w  w  . ja va2 s  .c  om*/

    if (StringUtils.endsWithIgnoreCase(attach.getContentType(), "pdf")) {
        PDDocument document = PDDocument.load(originalFile);
        List<PDPage> pages = document.getDocumentCatalog().getAllPages();
        PDPage page = pages.get(0);
        BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 72);
        ImageIO.write(Thumbnails.of(image).size(width, height).asBufferedImage(), "png", file);
        attach.setThumbnailSize((int) file.length());
        return file;
    } else if (StringUtils.startsWithIgnoreCase(attach.getContentType(), "image")) {
        BufferedImage originalImage = ImageIO.read(originalFile);
        if (originalImage.getHeight() < height || originalImage.getWidth() < width) {
            attach.setThumbnailSize(0);
            return originalFile;
        }
        BufferedImage thumbnail = Thumbnails.of(originalImage).size(width, height).asBufferedImage();
        ImageIO.write(thumbnail, "png", file);
        attach.setThumbnailSize((int) file.length());
        return file;
    }

    return null;
}

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox.PADESPDFBOXSigner.java

License:EUPL

@Override
public Image generateVisibleSignaturePreview(SignParameter parameter, java.security.cert.X509Certificate cert,
        int resolution, OperationStatus status, RequestedSignature requestedSignature) throws PDFASError {
    try {/*from  w w  w  . j  a  va 2 s.co  m*/
        PDFBOXObject pdfObject = (PDFBOXObject) status.getPdfObject();

        PDDocument origDoc = new PDDocument();
        origDoc.addPage(new PDPage(PDPage.PAGE_SIZE_A4));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        origDoc.save(baos);
        baos.close();

        pdfObject.setOriginalDocument(new ByteArrayDataSource(baos.toByteArray()));

        SignatureProfileSettings signatureProfileSettings = TableFactory
                .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings());

        // create Table describtion
        Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(),
                requestedSignature);

        IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings());

        IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main);

        SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

        String signaturePosString = signatureProfileConfiguration.getDefaultPositioning();
        PositioningInstruction positioningInstruction = null;
        if (signaturePosString != null) {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(signaturePosString), "",
                    origDoc, visualObject, false, false);
        } else {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(), "", origDoc,
                    visualObject, false, false);
        }

        origDoc.close();

        SignaturePositionImpl position = new SignaturePositionImpl();
        position.setX(positioningInstruction.getX());
        position.setY(positioningInstruction.getY());
        position.setPage(positioningInstruction.getPage());
        position.setHeight(visualObject.getHeight());
        position.setWidth(visualObject.getWidth());

        requestedSignature.setSignaturePosition(position);

        PDFAsVisualSignatureProperties properties = new PDFAsVisualSignatureProperties(
                pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject,
                positioningInstruction, signatureProfileSettings);

        properties.buildSignature();
        PDDocument visualDoc;
        synchronized (PDDocument.class) {
            visualDoc = PDDocument.load(properties.getVisibleSignature());
        }
        // PDPageable pageable = new PDPageable(visualDoc);
        List<PDPage> pages = new ArrayList<PDPage>();
        visualDoc.getDocumentCatalog().getPages().getAllKids(pages);

        PDPage firstPage = pages.get(0);

        float stdRes = 72;
        float targetRes = resolution;
        float factor = targetRes / stdRes;

        BufferedImage outputImage = firstPage.convertToImage(BufferedImage.TYPE_4BYTE_ABGR, (int) targetRes);

        BufferedImage cutOut = new BufferedImage((int) (position.getWidth() * factor),
                (int) (position.getHeight() * factor), BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D graphics = (Graphics2D) cutOut.getGraphics();

        graphics.drawImage(outputImage, 0, 0, cutOut.getWidth(), cutOut.getHeight(), (int) (1 * factor),
                (int) (outputImage.getHeight() - ((position.getHeight() + 1) * factor)),
                (int) ((1 + position.getWidth()) * factor), (int) (outputImage.getHeight()
                        - ((position.getHeight() + 1) * factor) + (position.getHeight() * factor)),
                null);
        return cutOut;
    } catch (PdfAsException e) {
        logger.warn("PDF-AS  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    } catch (Throwable e) {
        logger.warn("Unexpected Throwable  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox2.PADESPDFBOXSigner.java

License:EUPL

@Override
public Image generateVisibleSignaturePreview(SignParameter parameter, java.security.cert.X509Certificate cert,
        int resolution, OperationStatus status, RequestedSignature requestedSignature) throws PDFASError {
    try {/*from w ww .  java  2 s . com*/
        PDFBOXObject pdfObject = (PDFBOXObject) status.getPdfObject();

        PDDocument origDoc = new PDDocument();
        origDoc.addPage(new PDPage(PDRectangle.A4));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        origDoc.save(baos);
        baos.close();

        pdfObject.setOriginalDocument(new ByteArrayDataSource(baos.toByteArray()));

        SignatureProfileSettings signatureProfileSettings = TableFactory
                .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings());

        // create Table describtion
        Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(),
                requestedSignature);

        IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings());

        IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main);

        SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

        String signaturePosString = signatureProfileConfiguration.getDefaultPositioning();
        PositioningInstruction positioningInstruction = null;
        if (signaturePosString != null) {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(signaturePosString), "",
                    origDoc, visualObject, pdfObject.getStatus().getSettings());
        } else {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(), "", origDoc,
                    visualObject, pdfObject.getStatus().getSettings());
        }

        origDoc.close();

        SignaturePositionImpl position = new SignaturePositionImpl();
        position.setX(positioningInstruction.getX());
        position.setY(positioningInstruction.getY());
        position.setPage(positioningInstruction.getPage());
        position.setHeight(visualObject.getHeight());
        position.setWidth(visualObject.getWidth());

        requestedSignature.setSignaturePosition(position);

        PDFAsVisualSignatureProperties properties = new PDFAsVisualSignatureProperties(
                pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject,
                positioningInstruction, signatureProfileSettings);

        properties.buildSignature();
        PDDocument visualDoc;
        synchronized (PDDocument.class) {
            visualDoc = PDDocument.load(properties.getVisibleSignature());
        }
        // PDPageable pageable = new PDPageable(visualDoc);

        PDPage firstPage = visualDoc.getDocumentCatalog().getPages().get(0);

        float stdRes = 72;
        float targetRes = resolution;
        float factor = targetRes / stdRes;

        int targetPageNumber = 0;//TODO: is this always the case
        PDFRenderer pdfRenderer = new PDFRenderer(visualDoc);
        BufferedImage outputImage = pdfRenderer.renderImageWithDPI(targetPageNumber, targetRes, ImageType.ARGB);

        //BufferedImage outputImage = firstPage.convertToImage(BufferedImage.TYPE_4BYTE_ABGR, (int) targetRes);

        BufferedImage cutOut = new BufferedImage((int) (position.getWidth() * factor),
                (int) (position.getHeight() * factor), BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D graphics = (Graphics2D) cutOut.getGraphics();

        graphics.drawImage(outputImage, 0, 0, cutOut.getWidth(), cutOut.getHeight(), (int) (1 * factor),
                (int) (outputImage.getHeight() - ((position.getHeight() + 1) * factor)),
                (int) ((1 + position.getWidth()) * factor), (int) (outputImage.getHeight()
                        - ((position.getHeight() + 1) * factor) + (position.getHeight() * factor)),
                null);
        return cutOut;
    } catch (PdfAsException e) {
        logger.warn("PDF-AS  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    } catch (Throwable e) {
        logger.warn("Unexpected Throwable  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFAsTemplateCreator.java

License:EUPL

public InputStream buildPDF(PDFAsVisualSignatureDesigner properties, PDDocument originalDocument)
        throws IOException, PdfAsException {
    logger.debug("pdf building has been started");
    PDFTemplateStructure pdfStructure = pdfBuilder.getStructure();

    // we create array of [Text, ImageB, ImageC, ImageI]
    this.pdfBuilder.createProcSetArray();

    //create page
    this.pdfBuilder.createPage(properties);
    PDPage page = pdfStructure.getPage();

    //create template
    this.pdfBuilder.createTemplate(page);
    PDDocument template = pdfStructure.getTemplate();

    //create /AcroForm
    this.pdfBuilder.createAcroForm(template);
    PDAcroForm acroForm = pdfStructure.getAcroForm();

    // AcroForm contains singature fields
    this.pdfBuilder.createSignatureField(acroForm);
    PDSignatureField pdSignatureField = pdfStructure.getSignatureField();

    // create signature
    this.pdfBuilder.createSignature(pdSignatureField, page, properties.getSignatureFieldName());

    // that is /AcroForm/DR entry
    this.pdfBuilder.createAcroFormDictionary(acroForm, pdSignatureField);

    // create AffineTransform
    this.pdfBuilder.createAffineTransform(properties.getAffineTransformParams());
    //AffineTransform transform = pdfStructure.getAffineTransform();

    // rectangle, formatter, image. /AcroForm/DR/XObject contains that form
    this.pdfBuilder.createSignatureRectangle(pdSignatureField, properties,
            properties.getRotation() + properties.getPageRotation());
    this.pdfBuilder.createFormaterRectangle(properties.getFormaterRectangleParams());
    PDRectangle formater = pdfStructure.getFormatterRectangle();

    //this.pdfBuilder.createSignatureImage(template, properties.getImageStream());

    // create form stream, form and  resource. 
    this.pdfBuilder.createHolderFormStream(template);
    PDStream holderFormStream = pdfStructure.getHolderFormStream();
    this.pdfBuilder.createHolderFormResources();
    PDResources holderFormResources = pdfStructure.getHolderFormResources();
    this.pdfBuilder.createHolderForm(holderFormResources, holderFormStream, formater);

    // that is /AP entry the appearance dictionary.
    this.pdfBuilder.createAppearanceDictionary(pdfStructure.getHolderForm(), pdSignatureField,
            properties.getRotation() + properties.getPageRotation());

    // inner formstream, form and resource (hlder form containts inner form)
    this.pdfBuilder.createInnerFormStreamPdfAs(template, originalDocument);
    this.pdfBuilder.createInnerFormResource();
    PDResources innerFormResource = pdfStructure.getInnerFormResources();
    this.pdfBuilder.createInnerForm(innerFormResource, pdfStructure.getInnerFormStream(), formater);
    PDFormXObject innerForm = pdfStructure.getInnerForm();

    // inner form must be in the holder form as we wrote
    this.pdfBuilder.insertInnerFormToHolerResources(innerForm, holderFormResources);

    //  Image form is in this structure: /AcroForm/DR/FRM0/Resources/XObject/n0
    //this.pdfBuilder.createImageFormStream(template);
    //PDStream imageFormStream = pdfStructure.getImageFormStream();
    //this.pdfBuilder.createImageFormResources();
    //PDResources imageFormResources = pdfStructure.getImageFormResources();
    //this.pdfBuilder.createImageForm(imageFormResources, innerFormResource, imageFormStream, formater, transform,
    //        pdfStructure.getJpedImage());

    // now inject procSetArray
    /*this.pdfBuilder.injectProcSetArray(innerForm, page, innerFormResource, imageFormResources, holderFormResources,
        pdfStructure.getProcSet());*/
    this.pdfBuilder.injectProcSetArray(innerForm, page, innerFormResource, null, holderFormResources,
            pdfStructure.getProcSet());//from w w  w .j a  v  a 2s  . co  m

    /*String imgFormName = pdfStructure.getImageFormName();
    String imgName = pdfStructure.getImageName();*/
    String innerFormName = pdfStructure.getInnerFormName().getName();

    // now create Streams of AP
    /*this.pdfBuilder.injectAppearanceStreams(holderFormStream, imageFormStream, imageFormStream, imgFormName,
        imgName, innerFormName, properties);*/
    this.pdfBuilder.injectAppearanceStreams(holderFormStream, null, null, null, null, innerFormName,
            properties);
    this.pdfBuilder.createVisualSignature(template);
    this.pdfBuilder.createWidgetDictionary(pdSignatureField, holderFormResources);

    ByteArrayInputStream in = null;

    //COSDocument doc = pdfStructure.getVisualSignature();
    //doc.
    //in = pdfStructure.getTemplateAppearanceStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    template.save(baos);
    baos.close();

    SignatureProfileSettings signatureProfileSettings = this.pdfBuilder.signatureProfileSettings;

    boolean requirePDFA3 = signatureProfileSettings.isPDFA3();

    if (requirePDFA3) {

        //FileOutputStream fos = new FileOutputStream("/tmp/signature.pdf");
        //fos.write(baos.toByteArray());
        //fos.close();

        PDDocument cidSetRemoved = PDDocument.load(baos.toByteArray());
        try {
            this.pdfBuilder.removeCidSet(cidSetRemoved);
            baos.reset();
            baos = new ByteArrayOutputStream();
            cidSetRemoved.save(baos);
            baos.close();
        } finally {
            cidSetRemoved.close();
        }
    }

    in = new ByteArrayInputStream(baos.toByteArray());

    logger.debug("stream returning started, size= " + in.available());

    // we must close the document
    this.pdfBuilder.closeTemplate(template);

    // return result of the stream 
    return in;
}

From source file:au.org.alfred.icu.pdf.services.factories.ICUDischargeSummaryFactory.java

public static String loadDischargePDF(InputStream file) throws IOException {
    String pdf_str = null;//from   w  w  w . j a  va 2 s.c  o  m
    PDDocument doc = PDDocument.load(file);
    int pages = doc.getNumberOfPages();
    //System.out.println(pages);
    PDFTextStripper txt = new PDFTextStripper();
    txt.setStartPage(1);
    txt.setEndPage(1);
    pdf_str = txt.getText(doc);
    /*for(Iterator<COSObject> pdfItr = doc.getDocument().getObjects().iterator(); pdfItr.hasNext();)
     {
     COSObject inner = pdfItr.next();
            
            
     }*/
    //pdf_str = doc.getDocument().getObjects();
    doc.close();
    return pdf_str;
}

From source file:br.intercomex.pdfreader.PdrFeaderWS.java

private String getPdf(Blob pdf) throws SQLException, IOException {
    String text = null;//from  ww w.  jav a 2s  .  c om
    PDDocument document = PDDocument.load(pdf.getBinaryStream());
    PDFTextStripper stripper = new PDFTextStripper("UTF-16");
    text = stripper.getText(document);
    document.close();
    return text;
}

From source file:businessLogic.PrintManager.java

/**
 * printPDF creates the print job and sends it to the printer to be printed
 * @param fileName//from  w  ww  .jav  a 2 s  .c om
 * @param printer
 * @throws IOException
 * @throws PrinterException 
 */
public void printPDF(String fileName, PrintService printer) throws IOException, PrinterException {
    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintService(printer);
    PDDocument doc = PDDocument.load(fileName);
    doc.silentPrint(job);
}

From source file:ca.uqac.lif.labpal.FileHelper.java

License:Open Source License

/**
 * Merges multiple PDF files into a single file
 * @param dest The destination filename//from   www.j  ava  2  s . c om
 * @param paths The input files
 * @return The array of bytes containing the merged PDF
 */
@SuppressWarnings("deprecation")
public static byte[] mergePdf(String dest, String... paths) {
    try {
        ByteArrayOutputStream out = null;
        List<File> lst = new ArrayList<File>();
        List<PDDocument> lstPDD = new ArrayList<PDDocument>();
        for (String path : paths) {
            File file1 = new File(path);

            lstPDD.add(PDDocument.load(file1));
            lst.add(file1);
        }
        PDFMergerUtility PDFmerger = new PDFMergerUtility();

        // Setting the destination file
        PDFmerger.setDestinationFileName(dest);
        for (File file : lst) {
            // adding the source files
            PDFmerger.addSource(file);

        }
        // Merging the two documents
        PDFmerger.mergeDocuments();

        for (PDDocument pdd : lstPDD) {
            pdd.close();
        }

        PDDocument pdf = PDDocument.load(new File(dest));

        out = new ByteArrayOutputStream();

        pdf.save(out);
        byte[] data = out.toByteArray();
        pdf.close();
        return data;
    } catch (IOException e) {
        Logger.getAnonymousLogger().log(Level.SEVERE, e.getMessage());
    }
    return null;
}