org.apache.pdfbox.pdmodel.PDDocumentInformation Java Examples

The following examples show how to use org.apache.pdfbox.pdmodel.PDDocumentInformation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PdfTools.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public static PDDocument createPDF(File file, String author) {
    PDDocument targetDoc = null;
    try {
        PDDocument document = new PDDocument(AppVariables.pdfMemUsage);
        PDDocumentInformation info = new PDDocumentInformation();
        info.setCreationDate(Calendar.getInstance());
        info.setModificationDate(Calendar.getInstance());
        info.setProducer("MyBox v" + CommonValues.AppVersion);
        info.setAuthor(author);
        document.setDocumentInformation(info);
        document.setVersion(1.0f);
        document.save(file);
        targetDoc = document;
    } catch (Exception e) {
        logger.error(e.toString());
    }
    return targetDoc;
}
 
Example #2
Source File: PDFPainterBase.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void setMetadata(PDDocument doc) throws Exception {
	PDDocumentCatalog catalog = doc.getDocumentCatalog();
	PDDocumentInformation info = doc.getDocumentInformation();
	GregorianCalendar cal = new GregorianCalendar();
	cal.setTime(now);
	XMPMetadata metadata = new XMPMetadata();
	XMPSchemaPDF pdfSchema = metadata.addPDFSchema();
	pdfSchema.setKeywords(info.getKeywords());
	pdfSchema.setProducer(info.getProducer());
	XMPSchemaBasic basicSchema = metadata.addBasicSchema();
	basicSchema.setModifyDate(cal);
	basicSchema.setCreateDate(cal);
	basicSchema.setCreatorTool(info.getCreator());
	basicSchema.setMetadataDate(cal);
	XMPSchemaDublinCore dcSchema = metadata.addDublinCoreSchema();
	dcSchema.setTitle(info.getTitle());
	dcSchema.addCreator("PDFBox");
	dcSchema.setDescription(info.getSubject());
	PDMetadata metadataStream = new PDMetadata(doc);
	metadataStream.importXMPMetadata(metadata);
	catalog.setMetadata(metadataStream);
}
 
Example #3
Source File: MetadataExtractor.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Extract metadata from PDF
 */
public static PdfMetadata pdfExtractor(InputStream is) throws IOException {
	PDDocument doc = PDDocument.load(is);
	PDDocumentInformation info = doc.getDocumentInformation();
	PdfMetadata md = new PdfMetadata();

	md.setNumberOfPages(doc.getNumberOfPages());
	md.setTitle(info.getTitle());
	md.setAuthor(info.getAuthor());
	md.setSubject(info.getSubject());
	md.setKeywords(info.getKeywords());
	md.setCreator(info.getCreator());
	md.setProducer(info.getProducer());
	md.setTrapped(info.getTrapped());
	md.setCreationDate(info.getCreationDate());
	md.setModificationDate(info.getModificationDate());

	log.info("pdfExtractor: {}", md);
	return md;
}
 
Example #4
Source File: PdfSplitBatchController.java    From MyBox with Apache License 2.0 5 votes vote down vote up
private int writeFiles(List<PDDocument> docs) {
    int index = 1;
    try {
        if (docs == null || docs.isEmpty()) {
            return 0;
        }
        PDDocumentInformation info = new PDDocumentInformation();
        info.setCreationDate(Calendar.getInstance());
        info.setModificationDate(Calendar.getInstance());
        info.setProducer("MyBox v" + CommonValues.AppVersion);
        info.setAuthor(AppVariables.getUserConfigValue("AuthorKey", System.getProperty("user.name")));
        String targetPrefix = FileTools.getFilePrefix(currentParameters.currentSourceFile.getName());
        int total = docs.size();
        for (PDDocument pd : docs) {
            pd.setDocumentInformation(info);
            pd.setVersion(1.0f);
            PDPage page = pd.getPage(0);
            PDPageXYZDestination dest = new PDPageXYZDestination();
            dest.setPage(page);
            dest.setZoom(1f);
            dest.setTop((int) page.getCropBox().getHeight());
            PDActionGoTo action = new PDActionGoTo();
            action.setDestination(dest);
            pd.getDocumentCatalog().setOpenAction(action);

            String namePrefix = targetPrefix + "_" + StringTools.fillLeftZero(index++, (total + "").length());
            File tFile = makeTargetFile(namePrefix, ".pdf", currentParameters.currentTargetPath);
            pd.save(tFile);
            pd.close();

            targetFileGenerated(tFile);
        }
    } catch (Exception e) {
        logger.error(e.toString());
    }
    return index - 1;
}
 
Example #5
Source File: AlertReportExportPDF.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * adds PDF metadata to the PDF document
 *
 * @param extensionExport
 */
private void addMetaData(ExtensionAlertReportExport extensionExport) {
    PDDocumentInformation docInfo = document.getDocumentInformation();
    docInfo.setTitle(extensionExport.getParams().getTitleReport());
    docInfo.setSubject(extensionExport.getParams().getCustomerName());
    docInfo.setKeywords(extensionExport.getParams().getPdfKeywords());
    docInfo.setAuthor(extensionExport.getParams().getAuthorName());
    docInfo.setCreator(extensionExport.getParams().getAuthorName());
    docInfo.setProducer("OWASP ZAP. Extension authors: Leandro Ferrari, Colm O'Flaherty");
}
 
Example #6
Source File: ReportExportPDF.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * adds PDF metadata to the PDF document
 *
 * @param extensionExport
 */
private void addMetaData(ExtensionExportReport extensionExport) {
    PDDocumentInformation docInfo = document.getDocumentInformation();
    docInfo.setTitle(extensionExport.extensionGetTitle());
    docInfo.setSubject(extensionExport.extensionGetFor());
    docInfo.setKeywords("");
    docInfo.setAuthor(extensionExport.extensionGetBy());
    docInfo.setCreator(extensionExport.extensionGetBy());
    docInfo.setProducer("OWASP ZAP");
}
 
Example #7
Source File: PdfInformation.java    From MyBox with Apache License 2.0 4 votes vote down vote up
public void loadInformation() {
    try {
        if (doc == null) {
            return;
        }

        PDDocumentInformation docInfo = doc.getDocumentInformation();
        if (docInfo.getCreationDate() != null) {
            createTime = docInfo.getCreationDate().getTimeInMillis();
        }
        if (docInfo.getModificationDate() != null) {
            modifyTime = docInfo.getModificationDate().getTimeInMillis();
        }
        creator = docInfo.getCreator();
        producer = docInfo.getProducer();
        title = docInfo.getTitle();
        subject = docInfo.getSubject();
        author = docInfo.getAuthor();
        numberOfPages = doc.getNumberOfPages();
        keywords = docInfo.getKeywords();
        version = doc.getVersion();
        access = doc.getCurrentAccessPermission();

        PDPage page = doc.getPage(0);
        String size = "";
        PDRectangle box = page.getMediaBox();
        if (box != null) {
            size += "MediaBox: " + PdfTools.pixels2mm(box.getWidth()) + "mm * "
                    + PdfTools.pixels2mm(box.getHeight()) + "mm";
        }
        box = page.getTrimBox();
        if (box != null) {
            size += "  TrimBox: " + PdfTools.pixels2mm(box.getWidth()) + "mm * "
                    + PdfTools.pixels2mm(box.getHeight()) + "mm";
        }
        firstPageSize = size;
        size = "";
        box = page.getCropBox();
        if (box != null) {
            size += "CropBox: " + +PdfTools.pixels2mm(box.getWidth()) + "mm * "
                    + PdfTools.pixels2mm(box.getHeight()) + "mm";
        }
        box = page.getBleedBox();
        if (box != null) {
            size += "  BleedBox: " + +PdfTools.pixels2mm(box.getWidth()) + "mm * "
                    + PdfTools.pixels2mm(box.getHeight()) + "mm";
        }
        firstPageSize2 = size;
        outline = doc.getDocumentCatalog().getDocumentOutline();
        infoLoaded = true;
    } catch (Exception e) {
        logger.error(e.toString());
    }
}
 
Example #8
Source File: ImagesCombinePdfController.java    From MyBox with Apache License 2.0 4 votes vote down vote up
@FXML
@Override
public void saveAsAction() {
    if (tableData == null || tableData.isEmpty()) {
        return;
    }
    if (tableController.hasSampled()) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle(getMyStage().getTitle());
        alert.setContentText(AppVariables.message("SureSampled"));
        alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
        ButtonType buttonSure = new ButtonType(AppVariables.message("Sure"));
        ButtonType buttonCancel = new ButtonType(AppVariables.message("Cancel"));
        alert.getButtonTypes().setAll(buttonSure, buttonCancel);
        Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
        stage.setAlwaysOnTop(true);
        stage.toFront();

        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() != buttonSure) {
            return;
        }
    }

    final File file = chooseSaveFile(AppVariables.getUserConfigPath("PdfFilePath"),
            null, targetExtensionFilter, true);
    if (file == null) {
        return;
    }
    AppVariables.setUserConfigValue("PdfFilePath", file.getParent());
    recordFileWritten(file);
    synchronized (this) {
        if (task != null) {
            return;
        }
        task = new SingletonTask<Void>() {

            @Override
            protected boolean handle() {
                try {
                    try ( PDDocument document = new PDDocument(AppVariables.pdfMemUsage)) {
                        PDFont font = PdfTools.getFont(document, fontBox.getSelectionModel().getSelectedItem());
                        PDDocumentInformation info = new PDDocumentInformation();
                        info.setCreationDate(Calendar.getInstance());
                        info.setModificationDate(Calendar.getInstance());
                        info.setProducer("MyBox v" + CommonValues.AppVersion);
                        info.setAuthor(authorInput.getText());
                        document.setDocumentInformation(info);
                        document.setVersion(1.0f);
                        int count = 0;
                        int total = tableData.size();
                        for (Object source : tableData) {
                            if (task == null || isCancelled()) {
                                document.close();
                                return false;
                            }
                            ImageInformation imageInfo = (ImageInformation) source;
                            BufferedImage bufferedImage = ImageFileReaders.getBufferedImage(imageInfo);
                            if (bufferedImage != null) {
                                PdfTools.writePage(document, font, imageInfo.getImageFormat(), bufferedImage,
                                        ++count, total, pdfFormat,
                                        threshold, jpegQuality, isImageSize, pageNumberCheck.isSelected(),
                                        pageWidth, pageHeight, marginSize, headerInput.getText(), ditherCheck.isSelected());
                            }
                        }
                        document.save(file);
                        document.close();
                    }
                    return file.exists();

                } catch (Exception e) {
                    error = e.toString();
                    return false;
                }
            }

            @Override
            protected void whenSucceeded() {
                popSuccessful();
                if (viewCheck.isSelected()) {
                    view(file);
                }
            }

        };
        openHandlingStage(task, Modality.WINDOW_MODAL);
        Thread thread = new Thread(task);
        thread.setDaemon(true);
        thread.start();
    }
}
 
Example #9
Source File: PdfTools.java    From MyBox with Apache License 2.0 4 votes vote down vote up
public static boolean images2Pdf(List<Image> images, File targetFile,
        WeiboSnapParameters p) {
    try {
        if (images == null || images.isEmpty()) {
            return false;
        }
        int count = 0, total = images.size();
        try ( PDDocument document = new PDDocument(AppVariables.pdfMemUsage)) {
            PDDocumentInformation info = new PDDocumentInformation();
            info.setCreationDate(Calendar.getInstance());
            info.setModificationDate(Calendar.getInstance());
            info.setProducer("MyBox v" + CommonValues.AppVersion);
            info.setAuthor(p.getAuthor());
            document.setDocumentInformation(info);
            document.setVersion(1.0f);
            PDFont font = getFont(document, p.getFontName());

            BufferedImage bufferedImage;
            for (Image image : images) {
                if (null == p.getFormat()) {
                    bufferedImage = SwingFXUtils.fromFXImage(image, null);
                } else {
                    switch (p.getFormat()) {
                        case Tiff:
                            bufferedImage = SwingFXUtils.fromFXImage(image, null);
                            break;
                        case Jpeg:
                            bufferedImage = FxmlImageManufacture.checkAlpha(image, "jpg");
                            break;
                        default:
                            bufferedImage = SwingFXUtils.fromFXImage(image, null);
                            break;
                    }
                }
                imageInPdf(document, bufferedImage, p, ++count, total, font);
            }

            PDPage page = document.getPage(0);
            PDPageXYZDestination dest = new PDPageXYZDestination();
            dest.setPage(page);
            dest.setZoom(p.getPdfScale() / 100.0f);
            dest.setTop((int) page.getCropBox().getHeight());
            PDActionGoTo action = new PDActionGoTo();
            action.setDestination(dest);
            document.getDocumentCatalog().setOpenAction(action);

            document.save(targetFile);
            document.close();
            return true;
        }

    } catch (Exception e) {
        logger.error(e.toString());
        return false;
    }

}
 
Example #10
Source File: PdfUtils.java    From geoportal-server-harvester with Apache License 2.0 4 votes vote down vote up
/**
 * Reads metadata values from a PDF file.
 * 
 * @param rawBytes the PDF to read
 * @param defaultTitle title to be used if the PDF metadata doesn't have one
 * @param geometryServiceUrl url of a <a href="https://developers.arcgis.com/rest/services-reference/geometry-service.htm">geometry service</a> for reprojecting coordinates. 
 * 
 * @return metadata properties or null if the PDF cannot be read.
 * 
 * @throws IOException on parsing error
 */
public static Properties readMetadata(byte[] rawBytes, String defaultTitle, String geometryServiceUrl) throws IOException {
    Properties ret = new Properties();

    // Attempt to read in the PDF file
    try (PDDocument document = PDDocument.load(rawBytes)) {

        // See if we can read the PDF
        if (!document.isEncrypted()) {
            // Get document metadata
            PDDocumentInformation info = document.getDocumentInformation();

            if (info != null) {

                if (info.getTitle() != null) {
                    ret.put(PROP_TITLE, info.getTitle());
                } else {
                    ret.put(PROP_TITLE, defaultTitle);
                }

                if (info.getSubject() != null) {
                    ret.put(PROP_SUBJECT, info.getSubject());
                } else {

                    StringBuilder psudoSubject = new StringBuilder("");
                    psudoSubject.append("\nAuthor: " + info.getAuthor());
                    psudoSubject.append("\nCreator: " + info.getCreator());
                    psudoSubject.append("\nProducer: " + info.getProducer());

                    ret.put(PROP_SUBJECT, psudoSubject.toString());
                }

                if (info.getModificationDate() != null) {
                    ret.put(PROP_MODIFICATION_DATE, info.getModificationDate().getTime());
                } else if (info.getCreationDate() != null) {
                    ret.put(PROP_MODIFICATION_DATE, info.getCreationDate().getTime());
                }
            } else {
                LOG.warn("Got null metadata for PDF file");
                return null;
            }

            // Attempt to read in geospatial PDF data
            COSObject measure = document.getDocument().getObjectByType(COSName.getPDFName("Measure"));
            String bBox = null;
            if (measure != null) {
                // This is a Geospatial PDF (i.e. Adobe's standard)
                COSDictionary dictionary = (COSDictionary) measure.getObject();

                float[] coords = ((COSArray) dictionary.getItem("GPTS")).toFloatArray();

                bBox = generateBbox(coords);
            } else {
                PDPage page = document.getPage(0);
                if (page.getCOSObject().containsKey(COSName.getPDFName("LGIDict"))) {
                    // This is a GeoPDF (i.e. TerraGo's standard)
                    bBox = extractGeoPDFProps(page, geometryServiceUrl);
                }
            }

            if (bBox != null) {
                ret.put(PROP_BBOX, bBox);
            }

        } else {
            LOG.warn("Cannot read encrypted PDF file");
            return null;
        }

    } catch (IOException ex) {
        LOG.error("Exception reading PDF", ex);
        throw ex;
    }

    return ret;
}
 
Example #11
Source File: PDThread.java    From gcs with Mozilla Public License 2.0 2 votes vote down vote up
/**
 * Set the thread info, can be null.
 *
 * @param info The info dictionary about this thread.
 */
public void setThreadInfo( PDDocumentInformation info )
{
    thread.setItem( "I", info );
}
 
Example #12
Source File: PDFMergerUtility.java    From gcs with Mozilla Public License 2.0 2 votes vote down vote up
/**
 * Get the destination document information that is to be set in {@link #mergeDocuments(org.apache.pdfbox.io.MemoryUsageSetting)
 * }. The default is null, which means that it is ignored.
 *
 * @return The destination document information.
 */
public PDDocumentInformation getDestinationDocumentInformation()
{
    return destinationDocumentInformation;
}
 
Example #13
Source File: PDFMergerUtility.java    From gcs with Mozilla Public License 2.0 2 votes vote down vote up
/**
 * Set the destination document information that is to be set in {@link #mergeDocuments(org.apache.pdfbox.io.MemoryUsageSetting)
 * }. The default is null, which means that it is ignored.
 *
 * @param info The destination document information.
 */
public void setDestinationDocumentInformation(PDDocumentInformation info)
{
    destinationDocumentInformation = info;
}