Search in sources :

Example 1 with PreflightDocument

use of org.apache.pdfbox.preflight.PreflightDocument in project mustangproject by ZUGFeRD.

the class ZUGFeRDExporterFromA1Factory method getA1ParserValidationResult.

private static boolean getA1ParserValidationResult(PreflightParser parser) throws IOException {
    PreflightDocument document = null;
    try {
        /*
			 * Parse the PDF file with PreflightParser that inherits from the
			 * NonSequentialParser. Some additional controls are present to
			 * check a set of PDF/A requirements. (Stream length consistency,
			 * EOL after some Keyword...)
			 */
        parser.parse();
        /*
			 * Once the syntax validation is done, the parser can provide a
			 * PreflightDocument (that inherits from PDDocument) This document
			 * process the end of PDF/A validation.
			 */
        document = parser.getPreflightDocument();
        document.validate();
        // Get validation result
        return document.getResult().isValid();
    } catch (ValidationException e) {
        /*
			 * the parse method can throw a SyntaxValidationException if the PDF
			 * file can't be parsed. In this case, the exception contains an
			 * instance of ValidationResult
			 */
        return false;
    } finally {
        if (document != null) {
            document.close();
        }
    }
}
Also used : ValidationException(org.apache.pdfbox.preflight.exception.ValidationException) PreflightDocument(org.apache.pdfbox.preflight.PreflightDocument)

Example 2 with PreflightDocument

use of org.apache.pdfbox.preflight.PreflightDocument in project pdfbox by apache.

the class XmlResultParser method validate.

public Element validate(Document rdocument, DataSource source) throws IOException {
    String pdfType = null;
    ValidationResult result;
    long before = System.currentTimeMillis();
    try {
        PreflightParser parser = new PreflightParser(source);
        try {
            parser.parse();
            PreflightDocument document = parser.getPreflightDocument();
            document.validate();
            pdfType = document.getSpecification().getFname();
            result = document.getResult();
            document.close();
        } catch (SyntaxValidationException e) {
            result = e.getResult();
        }
    } catch (Exception e) {
        long after = System.currentTimeMillis();
        return generateFailureResponse(rdocument, source.getName(), after - before, pdfType, e);
    }
    long after = System.currentTimeMillis();
    if (result.isValid()) {
        Element preflight = generateResponseSkeleton(rdocument, source.getName(), after - before);
        // valid ?
        Element valid = rdocument.createElement("isValid");
        valid.setAttribute("type", pdfType);
        valid.setTextContent("true");
        preflight.appendChild(valid);
        return preflight;
    } else {
        Element preflight = generateResponseSkeleton(rdocument, source.getName(), after - before);
        // valid ?
        createResponseWithError(rdocument, pdfType, result, preflight);
        return preflight;
    }
}
Also used : SyntaxValidationException(org.apache.pdfbox.preflight.exception.SyntaxValidationException) Element(org.w3c.dom.Element) ValidationResult(org.apache.pdfbox.preflight.ValidationResult) PreflightDocument(org.apache.pdfbox.preflight.PreflightDocument) IOException(java.io.IOException) SyntaxValidationException(org.apache.pdfbox.preflight.exception.SyntaxValidationException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 3 with PreflightDocument

use of org.apache.pdfbox.preflight.PreflightDocument in project pdfbox by apache.

the class ICCProfileWrapper method searchFirstICCProfile.

/**
 * This method read all outputIntent dictionary until on of them have a destOutputProfile stream. This stream is
 * parsed and is used to create a IccProfileWrapper.
 *
 * @param context
 * @return an instance of ICCProfileWrapper or null if there are no DestOutputProfile
 * @throws ValidationException
 *             if an IOException occurs during the DestOutputProfile parsing
 */
private static ICCProfileWrapper searchFirstICCProfile(PreflightContext context) throws ValidationException {
    PreflightDocument document = context.getDocument();
    PDDocumentCatalog catalog = document.getDocumentCatalog();
    COSBase cBase = catalog.getCOSObject().getItem(COSName.getPDFName(DOCUMENT_DICTIONARY_KEY_OUTPUT_INTENTS));
    COSArray outputIntents = COSUtils.getAsArray(cBase, document.getDocument());
    for (int i = 0; outputIntents != null && i < outputIntents.size(); ++i) {
        COSDictionary outputIntentDict = COSUtils.getAsDictionary(outputIntents.get(i), document.getDocument());
        COSBase destOutputProfile = outputIntentDict.getItem(OUTPUT_INTENT_DICTIONARY_KEY_DEST_OUTPUT_PROFILE);
        if (destOutputProfile != null) {
            try {
                COSStream stream = COSUtils.getAsStream(destOutputProfile, document.getDocument());
                if (stream != null) {
                    InputStream is = stream.createInputStream();
                    try {
                        return new ICCProfileWrapper(ICC_Profile.getInstance(is));
                    } finally {
                        is.close();
                    }
                }
            } catch (IllegalArgumentException e) {
                context.addValidationError(new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_INVALID, "DestOutputProfile isn't a valid ICCProfile. Caused by : " + e.getMessage(), e));
            } catch (IOException e) {
                context.addValidationError(new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_INVALID, "Unable to parse the ICCProfile. Caused by : " + e.getMessage(), e));
            }
        }
    }
    return null;
}
Also used : COSStream(org.apache.pdfbox.cos.COSStream) COSArray(org.apache.pdfbox.cos.COSArray) COSDictionary(org.apache.pdfbox.cos.COSDictionary) InputStream(java.io.InputStream) COSBase(org.apache.pdfbox.cos.COSBase) ValidationError(org.apache.pdfbox.preflight.ValidationResult.ValidationError) IOException(java.io.IOException) PreflightDocument(org.apache.pdfbox.preflight.PreflightDocument) PDDocumentCatalog(org.apache.pdfbox.pdmodel.PDDocumentCatalog)

Example 4 with PreflightDocument

use of org.apache.pdfbox.preflight.PreflightDocument in project pdfbox by apache.

the class AbstractInvalidFileTester method validate.

@Test()
public final void validate() throws Exception {
    if (path == null) {
        logger.warn("This is an empty test");
        return;
    }
    PreflightDocument document = null;
    try {
        PreflightParser parser = new PreflightParser(path);
        parser.parse();
        document = parser.getPreflightDocument();
        document.validate();
        ValidationResult result = document.getResult();
        Assert.assertFalse(path + " : Isartor file should be invalid (" + path + ")", result.isValid());
        Assert.assertTrue(path + " : Should find at least one error", result.getErrorsList().size() > 0);
        // could contain more than one error
        boolean found = false;
        if (this.expectedError != null) {
            for (ValidationError error : result.getErrorsList()) {
                if (error.getErrorCode().equals(this.expectedError)) {
                    found = true;
                    if (outputResult == null) {
                        break;
                    }
                }
                if (outputResult != null) {
                    String log = path.getName().replace(".pdf", "") + "#" + error.getErrorCode() + "#" + error.getDetails() + "\n";
                    outputResult.write(log.getBytes());
                }
            }
        }
        if (result.getErrorsList().size() > 0) {
            if (this.expectedError == null) {
                logger.info("File invalid as expected (no expected code) :" + this.path.getAbsolutePath());
            } else if (!found) {
                StringBuilder message = new StringBuilder(100);
                message.append(path).append(" : Invalid error code returned. Expected ");
                message.append(this.expectedError).append(", found ");
                for (ValidationError error : result.getErrorsList()) {
                    message.append(error.getErrorCode()).append(" ");
                }
                Assert.fail(message.toString());
            }
        } else {
            Assert.assertEquals(path + " : Invalid error code returned.", this.expectedError, result.getErrorsList().get(0).getErrorCode());
        }
    } catch (ValidationException e) {
        throw new Exception(path + " :" + e.getMessage(), e);
    } finally {
        if (document != null) {
            document.close();
        }
    }
}
Also used : ValidationException(org.apache.pdfbox.preflight.exception.ValidationException) ValidationError(org.apache.pdfbox.preflight.ValidationResult.ValidationError) ValidationResult(org.apache.pdfbox.preflight.ValidationResult) PreflightParser(org.apache.pdfbox.preflight.parser.PreflightParser) PreflightDocument(org.apache.pdfbox.preflight.PreflightDocument) ValidationException(org.apache.pdfbox.preflight.exception.ValidationException) Test(org.junit.Test)

Example 5 with PreflightDocument

use of org.apache.pdfbox.preflight.PreflightDocument in project pdfbox by apache.

the class CreatePDFATest method testCreatePDFA.

/**
 * Test of doIt method of class CreatePDFA.
 */
public void testCreatePDFA() throws Exception {
    System.out.println("testCreatePDFA");
    String pdfaFilename = outDir + "/PDFA.pdf";
    String message = "The quick brown fox jumps over the lazy dog äöüÄÖÜß @°^²³ {[]}";
    String dir = "../pdfbox/src/main/resources/org/apache/pdfbox/resources/ttf/";
    String fontfile = dir + "LiberationSans-Regular.ttf";
    CreatePDFA.main(new String[] { pdfaFilename, message, fontfile });
    PreflightParser preflightParser = new PreflightParser(new File(pdfaFilename));
    preflightParser.parse();
    try (PreflightDocument preflightDocument = preflightParser.getPreflightDocument()) {
        preflightDocument.validate();
        ValidationResult result = preflightDocument.getResult();
        for (ValidationError ve : result.getErrorsList()) {
            System.err.println(ve.getErrorCode() + ": " + ve.getDetails());
        }
        assertTrue("PDF file created with CreatePDFA is not valid PDF/A-1b", result.isValid());
    }
    // check the XMP metadata
    PDDocument document = PDDocument.load(new File(pdfaFilename));
    PDDocumentCatalog catalog = document.getDocumentCatalog();
    PDMetadata meta = catalog.getMetadata();
    DomXmpParser xmpParser = new DomXmpParser();
    XMPMetadata metadata = xmpParser.parse(meta.createInputStream());
    DublinCoreSchema dc = metadata.getDublinCoreSchema();
    assertEquals(pdfaFilename, dc.getTitle());
    document.close();
}
Also used : XMPMetadata(org.apache.xmpbox.XMPMetadata) DomXmpParser(org.apache.xmpbox.xml.DomXmpParser) PDDocument(org.apache.pdfbox.pdmodel.PDDocument) ValidationError(org.apache.pdfbox.preflight.ValidationResult.ValidationError) PDMetadata(org.apache.pdfbox.pdmodel.common.PDMetadata) ValidationResult(org.apache.pdfbox.preflight.ValidationResult) DublinCoreSchema(org.apache.xmpbox.schema.DublinCoreSchema) PreflightParser(org.apache.pdfbox.preflight.parser.PreflightParser) File(java.io.File) PreflightDocument(org.apache.pdfbox.preflight.PreflightDocument) PDDocumentCatalog(org.apache.pdfbox.pdmodel.PDDocumentCatalog)

Aggregations

PreflightDocument (org.apache.pdfbox.preflight.PreflightDocument)10 ValidationResult (org.apache.pdfbox.preflight.ValidationResult)6 ValidationException (org.apache.pdfbox.preflight.exception.ValidationException)4 PreflightParser (org.apache.pdfbox.preflight.parser.PreflightParser)4 IOException (java.io.IOException)3 ValidationError (org.apache.pdfbox.preflight.ValidationResult.ValidationError)3 PDDocument (org.apache.pdfbox.pdmodel.PDDocument)2 PDDocumentCatalog (org.apache.pdfbox.pdmodel.PDDocumentCatalog)2 SyntaxValidationException (org.apache.pdfbox.preflight.exception.SyntaxValidationException)2 Test (org.junit.Test)2 File (java.io.File)1 InputStream (java.io.InputStream)1 DataSource (javax.activation.DataSource)1 FileDataSource (javax.activation.FileDataSource)1 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)1 COSArray (org.apache.pdfbox.cos.COSArray)1 COSBase (org.apache.pdfbox.cos.COSBase)1 COSDictionary (org.apache.pdfbox.cos.COSDictionary)1 COSDocument (org.apache.pdfbox.cos.COSDocument)1 COSStream (org.apache.pdfbox.cos.COSStream)1