org.apache.pdfbox.pdmodel.PDDocumentCatalog Java Examples

The following examples show how to use org.apache.pdfbox.pdmodel.PDDocumentCatalog. 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: PdfBleachSession.java    From DocBleach with MIT License 6 votes vote down vote up
void sanitize(RandomAccessRead source, OutputStream outputStream)
    throws IOException, BleachException {
  final PDDocument doc = getDocument(source);

  final PDDocumentCatalog docCatalog = doc.getDocumentCatalog();

  sanitizeNamed(doc, docCatalog.getNames());
  PDDocumentCatalogBleach catalogBleach = new PDDocumentCatalogBleach(this);
  catalogBleach.sanitize(docCatalog);
  sanitizeDocumentOutline(doc.getDocumentCatalog().getDocumentOutline());

  cosObjectBleach.sanitizeObjects(doc.getDocument().getObjects());

  doc.save(outputStream);
  doc.close();
}
 
Example #2
Source File: AbstractPdfBoxSignatureDrawer.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Method to check if the target image's colro space is present in the document's catalog
 * @param pdDocument {@link PDDocument} to check color profiles in
 * @param image {@link DSSDocument} image
 * @throws IOException in case of image reading error
 */
protected void checkColorSpace(PDDocument pdDocument, DSSDocument image) throws IOException {
	if (image != null) {
        PDDocumentCatalog catalog = pdDocument.getDocumentCatalog();
        List<PDOutputIntent> profiles = catalog.getOutputIntents();
        if (Utils.isCollectionEmpty(profiles)) {
        	LOG.warn("No color profile is present in the document. Not compatible with PDF/A");
        	return;
        }
			
		String colorSpaceName = getColorSpaceName(image);
   		if (COSName.DEVICECMYK.getName().equals(colorSpaceName) && isProfilePresent(profiles, RGB_PROFILE_NAME)) {
   			LOG.warn("A CMYK image will be added to an RGB color space PDF. Be aware: not compatible with PDF/A.");
   		} else if (COSName.DEVICERGB.getName().equals(colorSpaceName) && isProfilePresent(profiles, CMYK_PROFILE_NAME)) {
   			LOG.warn("An RGB image will be added to a CMYK color space PDF. Be aware: not compatible with PDF/A.");
   		}
	}
}
 
Example #3
Source File: FillInForm.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/52059931/pdfbox-setvalue-for-multiple-pdtextfield">
 * PDFBox setValue for multiple PDTextField
 * </a>
 * <br/>
 * <a href="https://ufile.io/z8jzj">
 * testform.pdf
 * </a>
 * <p>
 * Cannot reproduce the issue.
 * </p>
 */
@Test
public void testFillLikeJuvi() throws IOException {
    try (   InputStream originalStream = getClass().getResourceAsStream("testform.pdf") ) {
        PDDocument document = Loader.loadPDF(originalStream);
        PDDocumentCatalog docCatalog = document.getDocumentCatalog();
        PDAcroForm acroForm = docCatalog.getAcroForm();

        PDTextField field = (PDTextField) acroForm.getField("Check1");
        field.setValue("1111");

        PDTextField field2 = (PDTextField) acroForm.getField("Check2");
        field2.setValue("2222");

        PDTextField field3 = (PDTextField) acroForm.getField("HelloWorld");
        field3.setValue("HelloWorld");

        document.save(new File(RESULT_FOLDER, "testform-filled.pdf"));
        document.close();
    }
}
 
Example #4
Source File: PDDocumentCatalogBleachTest.java    From DocBleach with MIT License 6 votes vote down vote up
@Test
void sanitizeOpenAction() throws IOException {
  PDDocumentCatalog documentCatalog = mock(PDDocumentCatalog.class);

  when(documentCatalog.getOpenAction()).thenReturn(new PDActionJavaScript());
  instance.sanitizeOpenAction(documentCatalog);

  verify(documentCatalog, atLeastOnce()).getOpenAction();
  verify(documentCatalog, atLeastOnce()).setOpenAction(null);
  assertThreatsFound(session, 1);

  reset(session);
  reset(documentCatalog);

  when(documentCatalog.getOpenAction()).thenReturn(null);
  instance.sanitizeOpenAction(documentCatalog);
  verify(documentCatalog, atLeastOnce()).getOpenAction();
  verify(documentCatalog, never()).setOpenAction(null);

  assertThreatsFound(session, 0);
}
 
Example #5
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 #6
Source File: PDFMergerUtility.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private void mergeMarkInfo(PDDocumentCatalog destCatalog, PDDocumentCatalog srcCatalog)
{
    PDMarkInfo destMark = destCatalog.getMarkInfo();
    PDMarkInfo srcMark = srcCatalog.getMarkInfo();
    if (destMark == null)
    {
        destMark = new PDMarkInfo();
    }
    if (srcMark == null)
    {
        srcMark = new PDMarkInfo();
    }
    destMark.setMarked(true);
    destMark.setSuspect(srcMark.isSuspect() || destMark.isSuspect());
    destMark.setSuspect(srcMark.usesUserProperties() || destMark.usesUserProperties());
    destCatalog.setMarkInfo(destMark);
}
 
Example #7
Source File: FillAndFlatten.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/60964782/pdfbox-inconsistent-pdtextfield-behaviour-after-setvalue">
 * PDFBox Inconsistent PDTextField Behaviour after setValue
 * </a>
 * </br/>
 * <a href="https://s3-us-west-2.amazonaws.com/kx-filing-docs/b3-3.pdf">
 * b3-3.pdf
 * </a>
 * <p>
 * After removing the actions, PDFBox again sets appearances in
 * all fields.
 * </p>
 * @see #testLikeAbubakar()
 */
@Test
public void testLikeAbubakarRemoveAction() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("b3-3.pdf");
            PDDocument pdDocument = Loader.loadPDF(resource)    ) {
        PDDocumentCatalog catalog = pdDocument.getDocumentCatalog();
        PDAcroForm acroForm = catalog.getAcroForm();
        int i = 0;
        for (PDField field : acroForm.getFields()) {
            i=i+1;
            if (field instanceof PDTextField) {
                PDTextField textField = (PDTextField) field;
                textField.setActions(null);
                textField.setValue(Integer.toString(i));
            }
        }

        pdDocument.getDocumentCatalog().getAcroForm().flatten();

        pdDocument.save(new File(RESULT_FOLDER, "b3-3-remove-action-filled-and-flattened.pdf"));
    }
}
 
Example #8
Source File: PDFParser.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Extract the text from the form fields
 */
private void parseForm(PDDocument pdfDocument, StringBuffer content) throws IOException {
	PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog();
	PDAcroForm acroForm = docCatalog.getAcroForm();

	if (acroForm == null)
		return;

	content.append("\n");

	List<PDField> fields = acroForm.getFields();
	log.debug("{} top-level fields were found on the form", fields.size());

	for (PDField field : fields) {
		content.append(field.getPartialName());
		content.append(" = ");
		content.append(field.getValueAsString());
		content.append(" \n ");
	}
}
 
Example #9
Source File: LayerUtility.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Imports OCProperties from source document to target document so hidden layers can still be
 * hidden after import.
 *
 * @param sourceDoc The source PDF document that contains the /OCProperties to be copied.
 * @throws IOException If an I/O error occurs.
 */
private void importOcProperties(PDDocument srcDoc) throws IOException
{
    PDDocumentCatalog srcCatalog = srcDoc.getDocumentCatalog();
    PDOptionalContentProperties srcOCProperties = srcCatalog.getOCProperties();
    if (srcOCProperties == null)
    {
        return;
    }

    PDDocumentCatalog dstCatalog = targetDoc.getDocumentCatalog();
    PDOptionalContentProperties dstOCProperties = dstCatalog.getOCProperties();

    if (dstOCProperties == null)
    {
        dstCatalog.setOCProperties(new PDOptionalContentProperties(
                (COSDictionary) cloner.cloneForNewDocument(srcOCProperties)));
    }
    else
    {
        cloner.cloneMerge(srcOCProperties, dstOCProperties);
    }
}
 
Example #10
Source File: CreatePortableCollection.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/46642994/how-to-create-pdf-package-using-pdfbox">
 * How to create pdf package using PdfBox?
 * </a>
 * <p>
 * This test implements the equivalent of the OP's code turning
 * a regular PDF into a portable collection.
 * </p>
 */
@Test
public void test() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/pdfbox2/sign/test.pdf"))
    {
        PDDocument pdDocument = Loader.loadPDF(resource);

        COSDictionary collectionDictionary = new COSDictionary();
        collectionDictionary.setName(COSName.TYPE, "Collection");
        collectionDictionary.setName("View", "T");
        PDDocumentCatalog catalog = pdDocument.getDocumentCatalog();
        catalog.getCOSObject().setItem("Collection", collectionDictionary);

        pdDocument.save(new File(RESULT_FOLDER, "test-collection.pdf"));
    }
}
 
Example #11
Source File: FillAndFlatten.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/60964782/pdfbox-inconsistent-pdtextfield-behaviour-after-setvalue">
 * PDFBox Inconsistent PDTextField Behaviour after setValue
 * </a>
 * </br/>
 * <a href="https://s3-us-west-2.amazonaws.com/kx-filing-docs/b3-3.pdf">
 * b3-3.pdf
 * </a>
 * <p>
 * Indeed, PDFBox assumes in some fields that it should not create
 * field appearances which a formatting additional action would do
 * differently anyways in a viewer. In a flattening use case this is
 * obviously incorrect.
 * </p>
 * @see #testLikeAbubakarRemoveAction()
 */
@Test
public void testLikeAbubakar() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("b3-3.pdf");
            PDDocument pdDocument = Loader.loadPDF(resource)    ) {
        PDDocumentCatalog catalog = pdDocument.getDocumentCatalog();
        PDAcroForm acroForm = catalog.getAcroForm();
        int i = 0;
        for (PDField field : acroForm.getFields()) {
            i=i+1;
            if (field instanceof PDTextField) {
                PDTextField textField = (PDTextField) field;
                textField.setValue(Integer.toString(i));
            }
        }

        pdDocument.getDocumentCatalog().getAcroForm().flatten();

        pdDocument.save(new File(RESULT_FOLDER, "b3-3-filled-and-flattened.pdf"));
    }
}
 
Example #12
Source File: LayerUtility.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Places the given form over the existing content of the indicated page (like an overlay).
 * The form is enveloped in a marked content section to indicate that it's part of an
 * optional content group (OCG), here used as a layer. This optional group is returned and
 * can be enabled and disabled through methods on {@link PDOptionalContentProperties}.
 * <p>
 * You may want to call {@link #wrapInSaveRestore(PDPage) wrapInSaveRestore(PDPage)} before calling this method to make
 * sure that the graphics state is reset.
 *
 * @param targetPage the target page
 * @param form the form to place
 * @param transform the transformation matrix that controls the placement of your form. You'll
 * need this if your page has a crop box different than the media box, or if these have negative
 * coordinates, or if you want to scale or adjust your form.
 * @param layerName the name for the layer/OCG to produce
 * @return the optional content group that was generated for the form usage
 * @throws IOException if an I/O error occurs
 */
public PDOptionalContentGroup appendFormAsLayer(PDPage targetPage,
        PDFormXObject form, AffineTransform transform,
        String layerName) throws IOException
{
    PDDocumentCatalog catalog = targetDoc.getDocumentCatalog();
    PDOptionalContentProperties ocprops = catalog.getOCProperties();
    if (ocprops == null)
    {
        ocprops = new PDOptionalContentProperties();
        catalog.setOCProperties(ocprops);
    }
    if (ocprops.hasGroup(layerName))
    {
        throw new IllegalArgumentException("Optional group (layer) already exists: " + layerName);
    }

    PDRectangle cropBox = targetPage.getCropBox();
    if ((cropBox.getLowerLeftX() < 0 || cropBox.getLowerLeftY() < 0) && transform.isIdentity())
    {
        // PDFBOX-4044 
        LOG.warn("Negative cropBox " + cropBox + 
                 " and identity transform may make your form invisible");
    }

    PDOptionalContentGroup layer = new PDOptionalContentGroup(layerName);
    ocprops.addGroup(layer);

    PDPageContentStream contentStream = new PDPageContentStream(
            targetDoc, targetPage, AppendMode.APPEND, !DEBUG);
    contentStream.beginMarkedContent(COSName.OC, layer);
    contentStream.saveGraphicsState();
    contentStream.transform(new Matrix(transform));
    contentStream.drawForm(form);
    contentStream.restoreGraphicsState();
    contentStream.endMarkedContent();
    contentStream.close();

    return layer;
}
 
Example #13
Source File: RightAlignField.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/55355800/acroform-text-field-not-align-to-right">
 * acroform text field not align to right
 * </a>
 * <br/>
 * <a href="https://drive.google.com/uc?id=1jFbsYGFOnx8EMiHgDsE8LQtfwJHSa5Gh&export=download">
 * form.pdf 
 * </a> as "formBee2.pdf"
 * <p>
 * Indeed, in {@link #testAlignLikeBee()} quadding does not apply.
 * But by changing the order of field value setting and quadding
 * value setting it suddenly does apply.
 * </p>
 */
@Test
public void testAlignLikeBeeImproved() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("formBee2.pdf")    ) {
        PDDocument document = Loader.loadPDF(resource);
        PDDocumentCatalog documentCatalog = document.getDocumentCatalog();
        PDAcroForm acroForm = documentCatalog.getAcroForm();

        ((PDTextField) acroForm.getField("NewRentWithoutChargesChf")).setQ(PDVariableText.QUADDING_RIGHT);
        acroForm.getField("NewRentWithoutChargesChf").setValue("1.00");

        document.save(new File(RESULT_FOLDER, "formBee2-AlignLikeBeeImproved.pdf"));        
        document.close();
    }
}
 
Example #14
Source File: RightAlignField.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/55355800/acroform-text-field-not-align-to-right">
 * acroform text field not align to right
 * </a>
 * <br/>
 * <a href="https://drive.google.com/uc?id=1jFbsYGFOnx8EMiHgDsE8LQtfwJHSa5Gh&export=download">
 * form.pdf 
 * </a> as "formBee2.pdf"
 * <p>
 * Indeed, the way the OP does this, quadding does not apply.
 * But see {@link #testAlignLikeBeeImproved()}.
 * </p>
 */
@Test
public void testAlignLikeBee() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("formBee2.pdf")    ) {
        PDDocument document = Loader.loadPDF(resource);
        PDDocumentCatalog documentCatalog = document.getDocumentCatalog();
        PDAcroForm acroForm = documentCatalog.getAcroForm();

        acroForm.getField("NewRentWithoutChargesChf").setValue("1.00");
        ((PDTextField) acroForm.getField("NewRentWithoutChargesChf")).setQ(PDVariableText.QUADDING_RIGHT);

        document.save(new File(RESULT_FOLDER, "formBee2-AlignLikeBee.pdf"));        
        document.close();
    }
}
 
Example #15
Source File: AddFormField.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
     * <a href="https://stackoverflow.com/questions/46433388/pdfbox-could-not-find-font-helv">
     * PDFbox Could not find font: /Helv
     * </a>
     * <br/>
     * <a href="https://drive.google.com/file/d/0B2--NSDOiujoR3hOZFYteUl2UE0/view?usp=sharing">
     * 4.pdf
     * </a>
     * <p>
     * The cause is a combination of the OP and the source PDF not providing
     * a default appearance for the text field and PDFBox providing defaults
     * inconsequentially.
     * </p>
     * <p>
     * This is fixed here by setting the default appearance explicitly.
     * </p>
     */
    @Test
    public void testAddFieldLikeEugenePodoliako() throws IOException {
        try (   InputStream originalStream = getClass().getResourceAsStream("4.pdf") )
        {
            PDDocument pdf = Loader.loadPDF(originalStream);
            PDDocumentCatalog docCatalog = pdf.getDocumentCatalog();
            PDAcroForm acroForm = docCatalog.getAcroForm();
            PDPage page = pdf.getPage(0);

            PDTextField textBox = new PDTextField(acroForm);
            textBox.setPartialName("SampleField");
            acroForm.getFields().add(textBox);
            PDAnnotationWidget widget = textBox.getWidgets().get(0);
            PDRectangle rect = new PDRectangle(0, 0, 0, 0);
            widget.setRectangle(rect);
            widget.setPage(page);
//  Unnecessary code from OP
//            widget.setAppearance(acroForm.getFields().get(0).getWidgets().get(0).getAppearance());
//  Fix added to set default appearance accordingly
            textBox.setDefaultAppearance(acroForm.getFields().get(0).getCOSObject().getString("DA"));

            widget.setPrinted(false);

            page.getAnnotations().add(widget);

            acroForm.refreshAppearances();
            acroForm.flatten();
            pdf.save(new File(RESULT_FOLDER, "4-add-field.pdf"));
            pdf.close();
        }
    }
 
Example #16
Source File: PDFMergerUtility.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Merge the contents of the source form into the destination form for the
 * destination file.
 *
 * @param cloner the object cloner for the destination document
 * @param destAcroForm the destination form
 * @param srcAcroForm the source form
 * @throws IOException If an error occurs while adding the field.
 */
private void mergeAcroForm(PDFCloneUtility cloner, PDDocumentCatalog destCatalog,
        PDDocumentCatalog srcCatalog ) throws IOException
{
    try
    {
        PDAcroForm destAcroForm = destCatalog.getAcroForm();
        PDAcroForm srcAcroForm = srcCatalog.getAcroForm();
        
        if (destAcroForm == null && srcAcroForm != null)
        {
            destCatalog.getCOSObject().setItem(COSName.ACRO_FORM,
                    cloner.cloneForNewDocument(srcAcroForm.getCOSObject()));       
            
        }
        else
        {
            if (srcAcroForm != null)
            {
                if (acroFormMergeMode == AcroFormMergeMode.PDFBOX_LEGACY_MODE)
                {
                    acroFormLegacyMode(cloner, destAcroForm, srcAcroForm);
                }
                else if (acroFormMergeMode == AcroFormMergeMode.JOIN_FORM_FIELDS_MODE)
                {
                    acroFormJoinFieldsMode(cloner, destAcroForm, srcAcroForm);
                }
            }
        }
    }
    catch (IOException e)
    {
        // if we are not ignoring exceptions, we'll re-throw this
        if (!ignoreAcroFormErrors)
        {
            throw new IOException(e);
        }
    }
}
 
Example #17
Source File: PDFMergerUtility.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private void mergeOutputIntents(PDFCloneUtility cloner, 
        PDDocumentCatalog srcCatalog, PDDocumentCatalog destCatalog) throws IOException
{
    List<PDOutputIntent> srcOutputIntents = srcCatalog.getOutputIntents();
    List<PDOutputIntent> dstOutputIntents = destCatalog.getOutputIntents();
    for (PDOutputIntent srcOI : srcOutputIntents)
    {
        String srcOCI = srcOI.getOutputConditionIdentifier();
        if (srcOCI != null && !"Custom".equals(srcOCI))
        {
            // is that identifier already there?
            boolean skip = false;
            for (PDOutputIntent dstOI : dstOutputIntents)
            {
                if (dstOI.getOutputConditionIdentifier().equals(srcOCI))
                {
                    skip = true;
                    break;
                }
            }
            if (skip)
            {
                continue;
            }
        }
        destCatalog.addOutputIntent(new PDOutputIntent((COSDictionary) cloner.cloneForNewDocument(srcOI)));
        dstOutputIntents.add(srcOI);
    }
}
 
Example #18
Source File: PDFMergerUtility.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private void mergeLanguage(PDDocumentCatalog destCatalog, PDDocumentCatalog srcCatalog)
{
    if (destCatalog.getLanguage() == null && srcCatalog.getLanguage() != null)
    {
        destCatalog.setLanguage(srcCatalog.getLanguage());
    }
}
 
Example #19
Source File: PDDocumentCatalogBleach.java    From DocBleach with MIT License 5 votes vote down vote up
void sanitizeOpenAction(PDDocumentCatalog docCatalog)
    throws IOException {
  LOGGER.trace("Checking OpenAction...");
  PDDestinationOrAction openAction = docCatalog.getOpenAction();

  if (openAction == null) {
    return;
  }

  LOGGER.debug("Found a JavaScript OpenAction, removed. Was {}", openAction);
  docCatalog.setOpenAction(null);
  pdfBleachSession.recordJavascriptThreat("Document Catalog", "OpenAction");
}
 
Example #20
Source File: ReadXfaForm.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
public static byte[] getParsableXFAForm(InputStream file)
{
    if (file == null)
        return null;
    PDDocument doc;
    PDDocumentCatalog catalog;
    PDAcroForm acroForm;

    PDXFAResource xfa;
    try
    {
        // String pass = null;
        doc = Loader.loadPDF(file);
        if (doc == null)
            return null;
        // flattenPDF(doc);
        doc.setAllSecurityToBeRemoved(true);
        // System.out.println("Security " + doc.isAllSecurityToBeRemoved());
        catalog = doc.getDocumentCatalog();
        if (catalog == null)
        {
            doc.close();
            return null;
        }
        acroForm = catalog.getAcroForm();
        if (acroForm == null)
        {
            doc.close();
            return null;
        }
        xfa = acroForm.getXFA();
        if (xfa == null)
        {
            doc.close();
            return null;
        }
        // TODO return byte[]
        byte[] xfaBytes = xfa.getBytes();
        doc.close();
        return xfaBytes;
    } catch (IOException e)
    {
        // handle IOException
        // happens when the file is corrupt.
        e.printStackTrace();
        System.out.println("XFAUtils-getParsableXFAForm-IOException");
        return null;
    }
}
 
Example #21
Source File: PDFMergerUtility.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
private void mergeViewerPreferences(PDDocumentCatalog destCatalog, PDDocumentCatalog srcCatalog)
{
    PDViewerPreferences srcViewerPreferences = srcCatalog.getViewerPreferences();
    if (srcViewerPreferences == null)
    {
        return;
    }
    PDViewerPreferences destViewerPreferences = destCatalog.getViewerPreferences();
    if (destViewerPreferences == null)
    {
        destViewerPreferences = new PDViewerPreferences(new COSDictionary());
        destCatalog.setViewerPreferences(destViewerPreferences);
    }
    mergeInto(srcViewerPreferences.getCOSObject(), destViewerPreferences.getCOSObject(),
              Collections.<COSName>emptySet());

    // check the booleans - set to true if one is set and true
    if (srcViewerPreferences.hideToolbar() || destViewerPreferences.hideToolbar())
    {
        destViewerPreferences.setHideToolbar(true);
    }
    if (srcViewerPreferences.hideMenubar() || destViewerPreferences.hideMenubar())
    {
        destViewerPreferences.setHideMenubar(true);
    }
    if (srcViewerPreferences.hideWindowUI() || destViewerPreferences.hideWindowUI())
    {
        destViewerPreferences.setHideWindowUI(true);
    }
    if (srcViewerPreferences.fitWindow() || destViewerPreferences.fitWindow())
    {
        destViewerPreferences.setFitWindow(true);
    }
    if (srcViewerPreferences.centerWindow() || destViewerPreferences.centerWindow())
    {
        destViewerPreferences.setCenterWindow(true);
    }
    if (srcViewerPreferences.displayDocTitle() || destViewerPreferences.displayDocTitle())
    {
        destViewerPreferences.setDisplayDocTitle(true);
    }
}
 
Example #22
Source File: PDDocumentCatalogBleach.java    From DocBleach with MIT License 4 votes vote down vote up
void sanitize(PDDocumentCatalog docCatalog) throws IOException {
  sanitizeOpenAction(docCatalog);
  sanitizeDocumentActions(docCatalog.getActions());
  sanitizePageActions(docCatalog.getPages());
  sanitizeAcroFormActions(docCatalog.getAcroForm());
}
 
Example #23
Source File: PdfPanel.java    From swift-explorer with Apache License 2.0 4 votes vote down vote up
public synchronized void setPdf(PDDocument pdf) 
  {
  	listImagePages.clear();
      if (pdf == null)
      	return ;
try 
{
	if (pdf.isEncrypted())
	{
		logger.info("Failed attempt at previewing an encrypted PDF");
		return ;
	}
	PDDocumentCatalog cat = pdf.getDocumentCatalog() ;
	@SuppressWarnings("unchecked")
	List<PDPage> pages = cat.getAllPages() ;
       if (pages != null && !pages.isEmpty()) 
       {
       	for (PDPage page : pages)
       	{
       		listImagePages.add(page.convertToImage()) ;
       		if (listImagePages.size() >= maxPageToPreview)
       			break ;
       	}
       } 
} 
catch (IOException e) 
{
	logger.error("Error occurred while opening the pdf document", e);
}
finally 
{
	if (pdf != null)
	{
		try 
		{
			pdf.close();
		} 
		catch (IOException ex) 
		{
			logger.error("Error occurred while closing the pdf document", ex);
		}
	}
}
      repaint();
  }