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

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

Introduction

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

Prototype

public COSDocument getDocument() 

Source Link

Document

This will get the low level document.

Usage

From source file:io.konik.carriage.pdfbox.PDFBoxInvoiceAppender.java

License:Open Source License

@Override
public void append(AppendParameter appendParameter) {
    InputStream inputPdf = appendParameter.inputPdf();
    try {/*w w  w  .  ja v  a2s .c o  m*/
        PDDocument doc = PDDocument.load(inputPdf);
        setMetadata(doc, appendParameter);
        attachZugferdFile(doc, appendParameter.attachmentFile());
        doc.getDocument().setVersion(1.7f);
        doc.save(appendParameter.resultingPdf());
        doc.close();
    } catch (Exception e) {
        throw new InvoiceAppendError("Error appending Invoice", e);
    }

}

From source file:johnbrooksupgrade.PDFService.java

private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
    Salesman = txtNewUser.getText().isEmpty() ? cmbSalesPerson.getSelectedItem().toString()
            : txtNewUser.getText();// ww w. jav  a2 s  .  c  om
    Date = DateInput.getText();
    String ClientName = ClientnameInput.getText();
    String ProjectName = ProjectNameInput.getText();

    if (Branch == null) {
        JOptionPane.showMessageDialog(null, "Please Select a branch and try again.", "Error",
                JOptionPane.ERROR_MESSAGE);
    } else {
        /*** 
         * This is the logic that prints the information to a PDF 
         ***/

        //We want to save the file to Windows' temporary files folder so it can be loaded from there straight away
        //This temporary file is deleted when the program is exited
        File myfile = new File("C:\\Windows\\Temp\\ConveyorFile.pdf");

        //creates a new pdf
        if ((myfile) != null) {
            try {
                PDDocument doc;
                PDPage page;

                doc = new PDDocument();

                // Create a new blank page and add it to the document
                page = new PDPage();
                doc.addPage(page);
                PDFont font = PDType1Font.COURIER_BOLD;
                PDPageContentStream content = new PDPageContentStream(doc, page);
                content.beginText();
                content.setFont(font, 30);

                // creates a new page and gives it formatting of text
                content.moveTextPositionByAmount(110, 600);
                content.drawString("Technical Specifications ");
                PDFont font2 = PDType1Font.COURIER;
                content.setFont(font, 14);
                content.moveTextPositionByAmount(-50, -65);
                content.drawString("Date:" + Date);
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Sales person: " + Salesman);
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Client Name: " + ClientName);
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Project Name: " + ProjectName);
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Branch: " + Branch);
                content.moveTextPositionByAmount(0, -32);

                // Specifications    
                content.setFont(PDType1Font.COURIER_BOLD, 20);
                content.drawString("Specifications");
                content.moveTextPositionByAmount(0, -10);
                content.setFont(font, 14);
                content.moveTextPositionByAmount(10, -14);
                content.drawString("Speed of Belt M/pm: " + mainDataEntry.Speedofbeltanswer29f);
                content.moveTextPositionByAmount(0, -14);
                content.drawString(
                        "Drum/Sprocket  Mtrs: " + String.format("%.2f", mainDataEntry.Drumdiameterinput1));
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Metres per minute: " + mainDataEntry.getMetresperminuteanswer4f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Metres per hour: " + mainDataEntry.getMetresperhouranswer5f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Product per hour: " + mainDataEntry.getLengthperhouranswer7f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Kg's per hour: " + mainDataEntry.getKgsperhouranswer9f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Kg at any given time: " + mainDataEntry.getKgatanygiventimeanswer10f());
                content.moveTextPositionByAmount(-10, -28);

                // Results
                content.setFont(PDType1Font.COURIER_BOLD, 20);
                content.drawString("Results");
                content.moveTextPositionByAmount(0, -10);
                content.setFont(font, 14);
                content.moveTextPositionByAmount(10, -14);
                content.drawString("RPM: " + String.format("%.2f", mainDataEntry.getRpmconveyor34()));
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Application Factor: " + mainDataEntry.getRadiananswer25f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Pull Force Kg/f: " + mainDataEntry.PullForce);
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Nm Torque: " + mainDataEntry.getNmanswer15f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Service Factor: " + mainDataEntry.getServicefactor17f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Design Kw: " + mainDataEntry.getDesignkwanswer18f());
                content.moveTextPositionByAmount(-10, -28);

                // Gearbox recommendations 

                // only bother with section if the gearbox details aren't empty
                if (!mainDataEntry.GearboxDetailsForPDF.isEmpty()) {
                    content.setFont(PDType1Font.COURIER_BOLD, 20);
                    content.drawString("Gearbox/Motor Recommendations");
                    content.moveTextPositionByAmount(2, -25);
                    content.setFont(PDType1Font.COURIER_BOLD, 18);
                    content.drawString(mainDataEntry.GearboxType + ":");
                    content.setFont(font, 14);
                    content.moveTextPositionByAmount(10, -25);

                    String[] display;

                    // For the brooks cyclo we need to split the string by these values
                    // then write each index of the resulting array separately so the
                    // result doesn't just run off the page
                    display = mainDataEntry.GearboxDetailsForPDF.get(0).split("Ratio: |Overload ");

                    // Only need to do this when the string has been split out by Ratio or Overload
                    // i.e. this is only the case for brooks cyclo, the other two types fit the page fine
                    if (display.length > 1) {
                        display[1] = "Ratio: " + display[1];
                        content.drawString(display[0]);
                        content.moveTextPositionByAmount(0, -14);
                        content.drawString(display[1]);

                        if (display.length > 2) {
                            display[2] = "Overload " + display[2];
                            content.moveTextPositionByAmount(0, -14);
                            content.drawString(display[2]);
                        }
                    } else {
                        // first option must exist for the program to get this far
                        content.drawString(mainDataEntry.GearboxDetailsForPDF.get(0));
                    }

                    content.moveTextPositionByAmount(0, -14);

                    // only bother with the second option if it exists
                    if (mainDataEntry.GearboxDetailsForPDF.size() > 1) {
                        display = mainDataEntry.GearboxDetailsForPDF.get(1).split("Ratio: |Overload ");

                        if (display.length > 1) {
                            content.moveTextPositionByAmount(0, -15);
                            display[1] = "Ratio: " + display[1];
                            content.drawString(display[0]);
                            content.moveTextPositionByAmount(0, -14);
                            content.drawString(display[1]);

                            if (display.length > 2) {
                                display[2] = "Overload " + display[2];
                                content.moveTextPositionByAmount(0, -14);
                                content.drawString(display[2]);
                            }
                        } else {
                            content.moveTextPositionByAmount(0, -14);
                            content.drawString(mainDataEntry.GearboxDetailsForPDF.get(1));
                        }
                    }
                }

                content.endText();

                image2 = ImageIO.read(new File("logosmall.jpg"));
                BufferedImage logo = image2;
                // writes the image to the file

                PDXObjectImage jblogo = new PDPixelMap(doc, logo);

                content.drawImage(jblogo, 20, 650);
                //postions image
                content.close();
                doc.getDocument();
                doc.save(myfile.getAbsolutePath());

                // open the file 
                Desktop.getDesktop().open(myfile);

                doc.close();
                close();
                //saves pdf and closes it
            } catch (IOException | COSVisitorException ie) {
                JOptionPane.showMessageDialog(null, ie.getMessage(), "Error!", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }
}

From source file:modules.PDFFontDependencyExtractorModule.java

License:Apache License

public PDFFontResults extractFontList(File f) throws IOException, InvalidParameterException {
    PDDocument document;
    try {//ww w . j a  va2s. com
        document = PDDocument.load(f);
    } catch (IOException x) {
        throw new InvalidParameterException("Not a PDF file");
    }
    SortedSet<FontInformation> ret = new TreeSet<FontInformation>(new Comparator<FontInformation>() {

        @Override
        public int compare(FontInformation o1, FontInformation o2) {
            int a = o1.fontName.compareTo(o2.fontName);
            if (a != 0)
                return a;
            else
                return o1.fontType.compareTo(o2.fontType);
        }

    });

    document.getDocumentCatalog().getAllPages();
    // The code down here is easier as it gets all the fonts used in the
    // document. Still, this would inlcude unused fonts, so we get the fonts
    // page by page and add them to a Hash table.
    for (COSObject c : document.getDocument().getObjectsByType(COSName.FONT)) {
        if (c == null || !(c.getObject() instanceof COSDictionary)) {
            continue;
            // System.out.println(c.getObject());
        }

        COSDictionary fontDictionary = (COSDictionary) c.getObject();
        // System.out.println(dic.getNameAsString(COSName.BASE_FONT));
        // }
        // }
        // int pagen = document.getNumberOfPages();
        // i=0;
        // for (int p=0;p<pagen;p++){
        // PDPage page = (PDPage)pages.get(p);
        // PDResources res = page.findResources();
        // //for each page resources
        // if (res==null) continue;
        // // get the font dictionary
        // COSDictionary fonts = (COSDictionary)
        // res.getCOSDictionary().getDictionaryObject( COSName.FONT );
        // for( COSName fontName : fonts.keySet() ) {
        // COSObject font = (COSObject) fonts.getItem( fontName );
        // // if the font has already been visited we ingore it
        // long objectId = font.getObjectNumber().longValue();
        // if (ret.get(objectId)!=null)
        // continue;
        // if( font==null || ! (font.getObject() instanceof COSDictionary) )
        // continue;
        // COSDictionary fontDictionary = (COSDictionary)font.getObject();

        // Type MUSt be font
        if (!fontDictionary.getNameAsString(COSName.TYPE).equals("Font")) {
            continue;
        }
        // get the variables
        FontInformation fi = new FontInformation();
        fi.fontType = fontDictionary.getNameAsString(COSName.SUBTYPE);

        String baseFont = fontDictionary.getNameAsString(COSName.BASE_FONT);
        if (baseFont == null) {
            continue;
        }
        if (Arrays.binarySearch(standard14, baseFont) >= 0) {
            continue;
        }
        COSDictionary fontDescriptor = (COSDictionary) fontDictionary.getDictionaryObject(COSName.FONT_DESC);
        COSBase enc = fontDictionary.getItem(COSName.ENCODING);
        COSBase uni = fontDictionary.getItem(COSName.TO_UNICODE);
        fontDictionary.getInt(COSName.FIRST_CHAR);
        fontDictionary.getInt(COSName.LAST_CHAR);
        String encoding;
        boolean toUnicode = uni != null;
        if (enc == null) {
            encoding = "standard14";
        }
        if (enc instanceof COSString) {
            encoding = ((COSString) enc).getString();
        } else {
            encoding = "table";
        }
        fi.isSubset = false;
        boolean t = true;
        // Type one and TT can have subsets defineing the basename see 5.5.3
        // pdfref 1.6
        // if (fi.fontType.lastIndexOf(COSName.TYPE1.getName())!=-1 ||
        // fi.fontType.equals(COSName.TRUE_TYPE.getName()) )
        if (baseFont != null) {
            if (baseFont.length() > 6) {
                for (int k = 0; k < 6; k++)
                    if (!Character.isUpperCase(baseFont.charAt(k))) {
                        t = false;
                    }
                if (baseFont.charAt(6) != '+') {
                    t = false;
                }
            } else {
                t = false;
            }
            fi.isSubset = t;
            if (fi.isSubset) {
                fi.baseName = baseFont.substring(0, 6);
                baseFont = baseFont.substring(7);
            }
        }
        fi.fontFlags = 0;
        if (fi.fontType.equals(COSName.TYPE0.getName()) || fi.fontType.equals(COSName.TYPE3.getName())) {
            fi.isEmbedded = true;
        }

        if (fontDescriptor != null) {
            // in Type1 charset indicates font is subsetted
            if (fontDescriptor.getItem(COSName.CHAR_SET) != null) {
                fi.isSubset = true;
            }
            if (fontDescriptor.getItem(COSName.FONT_FILE) != null
                    || fontDescriptor.getItem(COSName.FONT_FILE3) != null
                    || fontDescriptor.getItem(COSName.FONT_FILE2) != null) {
                fi.isEmbedded = true;
            }
            fi.fontFlags = fontDescriptor.getInt(COSName.getPDFName("Flags"));
            fi.fontFamily = fontDescriptor.getString(COSName.FONT_FAMILY);
            fi.fontStretch = fontDescriptor.getString(COSName.FONT_STRETCH);

        }
        fi.charset = encoding;
        fi.fontName = baseFont;
        fi.isToUnicode = toUnicode;
        fi.encoding = fontDictionary.getNameAsString(COSName.CID_TO_GID_MAP);

        ret.add(fi);

    } // for all fonts

    HashMultimap<String, FontInformation> m = HashMultimap.create();

    for (FontInformation ff : ret) {
        m.put(ff.fontName, ff);
    }
    LinkedList<FontInformation> missing = new LinkedList<FontInformation>();
    Set<String> k = m.keySet();
    for (String kk : k) {
        Set<FontInformation> s = m.get(kk);
        if (s.size() < 1) {
            continue;
        }
        if (s.size() > 1) {
            boolean found = false;
            FontInformation ff = null;
            for (FontInformation fonti : s) {
                if (!fonti.isEmbedded) {
                    ff = fonti;
                } else {
                    found = true;
                }
            }
            if (!found) {
                missing.add(ff);
            }
        } else {
            FontInformation ff = s.iterator().next();
            if (!ff.isEmbedded) {
                missing.add(ff);
            }
        }

    }

    // } // for all pages
    // Iterator<FontInformation> it = ret.iterator();
    // FontInformation prev = null;
    // LinkedList<FontInformation> toDelete = new
    // LinkedList<FontInformation>();
    // while (it.hasNext()) {
    // FontInformation current = it.next();
    //
    // if (prev!= null && prev.fontName.equals(current.fontName) &&
    // (prev.fontType.startsWith("CIDFontType") ||
    // current.fontType.startsWith("CIDFontType")))
    // toDelete.add(current);
    // prev = current;
    // }
    //
    // //ret.removeAll(toDelete);
    // FontInformation[] retArray =toDelete.toArray(new FontInformation[0]);
    //

    if (missing.size() == 0) {
        missing = null;
    } else {
        System.out.println("Found missing fonts: " + f);
        System.out.println(missing);
    }
    return new PDFFontResults(new LinkedList<FontInformation>(ret), missing);
}

From source file:net.awl.edoc.pdfa.PdfBoxIsartorValidate.java

License:Apache License

public static void coin(File f) {
    nbFile++;/*from   ww w.ja  v a  2  s .com*/
    // PDFBox
    try {
        PDDocument document = PDDocument.load(f);
        COSDocument cDocument = document.getDocument();

        boolean result = PDFParser.parse(new FileInputStream(f));
        if (result) {
            nbOk++;
        } else {
            nbBad++;
        }
        ;

        document.close();
    } catch (IOException e) {
        System.err.println("Failed for : " + f.getAbsolutePath());
        // } catch (ParseException e) {
        // nbBad++;
    } catch (Throwable e) {
        nbBad++;
    }

}

From source file:net.padaf.preflight.helpers.CatalogValidationHelper.java

License:Apache License

/**
 * This method checks the content of each OutputIntent. The S entry must
 * contain GTS_PDFA1. The DestOuputProfile must contain a valid ICC Profile
 * Stream./*from  w w  w. j a  va  2s.  c o  m*/
 * 
 * If there are more than one OutputIntent, they have to use the same ICC
 * Profile.
 * 
 * This method returns a list of ValidationError. It is empty if no errors
 * have been found.
 * 
 * @param handler
 * @return
 * @throws ValidationException
 */
public List<ValidationError> validateOutputIntent(DocumentHandler handler) throws ValidationException {
    List<ValidationError> result = new ArrayList<ValidationError>(0);
    PDDocument pdDocument = handler.getDocument();
    PDDocumentCatalog catalog = pdDocument.getDocumentCatalog();
    COSDocument cDoc = pdDocument.getDocument();

    COSBase cBase = catalog.getCOSDictionary()
            .getItem(COSName.getPDFName(DOCUMENT_DICTIONARY_KEY_OUTPUT_INTENTS));
    COSArray outputIntents = COSUtils.getAsArray(cBase, cDoc);

    Map<COSObjectKey, Boolean> tmpDestOutputProfile = new HashMap<COSObjectKey, Boolean>();

    for (int i = 0; outputIntents != null && i < outputIntents.size(); ++i) {
        COSDictionary dictionary = COSUtils.getAsDictionary(outputIntents.get(i), cDoc);

        if (dictionary == null) {

            result.add(new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY,
                    "OutputIntent object is null or isn't a dictionary"));

        } else {
            // ---- S entry is mandatory and must be equals to GTS_PDFA1
            String sValue = dictionary.getNameAsString(COSName.getPDFName(OUTPUT_INTENT_DICTIONARY_KEY_S));
            if (!OUTPUT_INTENT_DICTIONARY_VALUE_GTS_PDFA1.equals(sValue)) {
                result.add(new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_S_VALUE_INVALID,
                        "The S entry of the OutputIntent isn't GTS_PDFA1"));
                continue;
            }

            // ---- OutputConditionIdentifier is a mandatory field
            String outputConditionIdentifier = dictionary
                    .getString(COSName.getPDFName(OUTPUT_INTENT_DICTIONARY_KEY_OUTPUT_CONDITION_IDENTIFIER));
            if (outputConditionIdentifier == null || "".equals(outputConditionIdentifier)) {
                result.add(new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY,
                        "The OutputIntentCondition is missing"));
                continue;
            }

            // ---- If OutputConditionIdentifier is "Custom" :
            // ---- DestOutputProfile and Info are mandatory
            // ---- DestOutputProfile must be a ICC Profile

            // ---- Because of PDF/A conforming file needs to specify the color
            // characteristics, the DestOutputProfile
            // is checked even if the OutputConditionIdentifier isn't "Custom"
            COSBase dop = dictionary
                    .getItem(COSName.getPDFName(OUTPUT_INTENT_DICTIONARY_KEY_DEST_OUTPUT_PROFILE));
            ValidationError valer = validateICCProfile(dop, cDoc, tmpDestOutputProfile, handler);
            if (valer != null) {
                result.add(valer);
                continue;
            }

            if (OUTPUT_INTENT_DICTIONARY_VALUE_OUTPUT_CONDITION_IDENTIFIER_CUSTOM
                    .equals(outputConditionIdentifier)) {
                String info = dictionary.getString(COSName.getPDFName(OUTPUT_INTENT_DICTIONARY_KEY_INFO));
                if (info == null || "".equals(info)) {
                    result.add(new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY,
                            "The Info entry of a OutputIntent dictionary is missing"));
                    continue;
                }
            }
        }
    }
    return result;
}

From source file:net.padaf.preflight.helpers.FileSpecificationValidationHelper.java

License:Apache License

@Override
public List<ValidationError> innerValidate(DocumentHandler handler) throws ValidationException {
    List<ValidationError> result = new ArrayList<ValidationError>(0);
    PDDocument pdfDoc = handler.getDocument();
    COSDocument cDoc = pdfDoc.getDocument();

    List<?> lCOSObj = cDoc.getObjects();
    for (Object o : lCOSObj) {
        COSObject cObj = (COSObject) o;//w w w  .j av a2s .  co m

        // ---- If this object represents a Stream
        // The Dictionary must contain the Length key
        COSBase cBase = cObj.getObject();
        if (cBase instanceof COSDictionary) {
            COSDictionary dic = (COSDictionary) cBase;
            String type = dic.getNameAsString(COSName.getPDFName(DICTIONARY_KEY_TYPE));
            if (FILE_SPECIFICATION_VALUE_TYPE.equals(type)) {
                // ---- It is a file specification
                result.addAll(validateFileSpecification(handler, cObj));
            }
        }
    }
    return result;
}

From source file:net.padaf.preflight.helpers.FontValidationHelper.java

License:Apache License

@Override
public List<ValidationError> innerValidate(DocumentHandler handler) throws ValidationException {
    List<ValidationError> result = new ArrayList<ValidationError>(0);
    PDDocument pdfDoc = handler.getDocument();
    COSDocument cDoc = pdfDoc.getDocument();

    List<?> lCOSObj = cDoc.getObjects();

    List<FontValidator> lType3 = new ArrayList<FontValidator>();

    for (Object o : lCOSObj) {
        COSObject cObj = (COSObject) o;/*ww  w.j av a 2s.c  o m*/

        // If this object represents a Stream, the Dictionary must contain the
        // Length key
        COSBase cBase = cObj.getObject();
        if (cBase instanceof COSDictionary) {
            COSDictionary dic = (COSDictionary) cBase;
            String type = dic.getNameAsString(COSName.getPDFName(DICTIONARY_KEY_TYPE));
            if (type != null && FONT_DICTIONARY_VALUE_FONT.equals(type)) {
                FontValidator fontVal = fontValidationFactory.getFontValidator(cObj, handler);
                if (fontVal instanceof Type3FontValidator) {
                    lType3.add(fontVal);
                } else {
                    validateFont(handler, fontVal, result);
                }
            }
        }
    }

    // ---- Type 3 can contain other font, so type 3 are validated at the end.
    for (FontValidator t3FontVal : lType3) {
        validateFont(handler, t3FontVal, result);
    }

    return result;
}

From source file:net.padaf.preflight.helpers.GraphicsValidationHelper.java

License:Apache License

@Override
public List<ValidationError> innerValidate(DocumentHandler handler) throws ValidationException {
    List<ValidationError> result = new ArrayList<ValidationError>(0);
    PDDocument pdfDoc = handler.getDocument();

    // ---- Checks all XObjects
    COSDocument cDoc = pdfDoc.getDocument();
    List<?> lCOSObj = cDoc.getObjects();
    for (Object o : lCOSObj) {
        COSObject cObj = (COSObject) o;/*from  w w w  . j  a v a2s  .c  o m*/
        COSBase cBase = cObj.getObject();
        if (cBase instanceof COSDictionary) {
            COSDictionary dic = (COSDictionary) cBase;
            String type = dic.getNameAsString(COSName.getPDFName(DICTIONARY_KEY_TYPE));
            if (type != null && DICTIONARY_KEY_XOBJECT.equals(type)) {
                result.addAll(validateXObject(handler, cObj));
            } else if (type != null && DICTIONARY_KEY_PATTERN.equals(type)) {
                result.addAll(validatePattern(handler, cObj));
            }
        }
    }
    return result;
}

From source file:net.padaf.preflight.helpers.MetadataValidationHelper.java

License:Apache License

public List<ValidationError> innerValidate(DocumentHandler handler) throws ValidationException {
    try {// w  ww .j av  a 2 s. c om
        PDDocument document = handler.getDocument();

        byte[] tmp = getXpacket(document.getDocument());
        XMPDocumentBuilder builder;
        try {
            builder = new XMPDocumentBuilder();
        } catch (XmpSchemaException e1) {
            throw new ValidationException(e1.getMessage(), e1);
        }
        XMPMetadata metadata;
        try {
            metadata = builder.parse(tmp);
            handler.setMetadata(metadata);
        } catch (XmpSchemaException e) {
            throw new ValidationException("Parser: Internal Problem (failed to instanciate Schema object)", e);
        } catch (XmpXpacketEndException e) {
            throw new ValidationException("Unable to parse font metadata due to : " + e.getMessage(), e);
        }
        List<ValidationError> lve = new ArrayList<ValidationError>();

        // 6.7.5 no deprecated attribute in xpacket processing instruction
        if (metadata.getXpacketBytes() != null) {
            lve.add(new ValidationError(ValidationConstants.ERROR_METADATA_XPACKET_DEPRECATED,
                    "bytes attribute is forbidden"));
        }
        if (metadata.getXpacketEncoding() != null) {
            lve.add(new ValidationError(ValidationConstants.ERROR_METADATA_XPACKET_DEPRECATED,
                    "encoding attribute is forbidden"));
        }

        // Call metadata synchronization checking
        lve.addAll(new SynchronizedMetaDataValidation().validateMetadataSynchronization(document, metadata));

        // Call PDF/A Identifier checking
        lve.addAll(new PDFAIdentificationValidation().validatePDFAIdentifer(metadata));

        // Call rdf:about checking
        try {
            new RDFAboutAttributeConcordanceValidation().validateRDFAboutAttributes(metadata);
        } catch (DifferentRDFAboutException e) {
            lve.add(new ValidationError(ValidationConstants.ERROR_METADATA_RDF_ABOUT_ATTRIBUTE_INEQUAL_VALUE,
                    e.getMessage()));
        }

        return lve;
    } catch (XpacketParsingException e) {
        List<ValidationError> lve = new ArrayList<ValidationError>();
        if (e.getError() != null) {
            lve.add(e.getError());
        } else {
            lve.add(new ValidationError(ValidationConstants.ERROR_METADATA_MAIN, "Unexpected error"));
        }
        return lve;
    } catch (XmpPropertyFormatException e) {
        List<ValidationError> lve = new ArrayList<ValidationError>();
        lve.add(new ValidationError(ValidationConstants.ERROR_METADATA_PROPERTY_FORMAT, e.getMessage()));
        return lve;
    } catch (BadFieldValueException e) {
        List<ValidationError> lve = new ArrayList<ValidationError>();
        lve.add(new ValidationError(ValidationConstants.ERROR_METADATA_CATEGORY_PROPERTY_INVALID,
                e.getMessage()));
        return lve;
    } catch (XmpExpectedRdfAboutAttribute e) {
        List<ValidationError> lve = new ArrayList<ValidationError>();
        lve.add(new ValidationError(ValidationConstants.ERROR_METADATA_RDF_ABOUT_ATTRIBUTE_MISSING,
                e.getMessage()));
        return lve;
    } catch (XmpUnknownPropertyException e) {
        List<ValidationError> lve = new ArrayList<ValidationError>();
        lve.add(new ValidationError(ValidationConstants.ERROR_METADATA_PROPERTY_UNKNOWN, e.getMessage()));
        return lve;
    } catch (XmpUnknownSchemaException e) {
        List<ValidationError> lve = new ArrayList<ValidationError>();
        lve.add(new ValidationError(ValidationConstants.ERROR_METADATA_ABSENT_DESCRIPTION_SCHEMA,
                e.getMessage()));
        return lve;
    } catch (XmpUnexpectedNamespaceURIException e) {
        List<ValidationError> lve = new ArrayList<ValidationError>();
        lve.add(new ValidationError(ValidationConstants.ERROR_METADATA_WRONG_NS_URI, e.getMessage()));
        return lve;
    } catch (XmpUnexpectedNamespacePrefixException e) {
        List<ValidationError> lve = new ArrayList<ValidationError>();
        lve.add(new ValidationError(ValidationConstants.ERROR_METADATA_ABSENT_DESCRIPTION_SCHEMA,
                e.getMessage()));
        return lve;
    } catch (XmpRequiredPropertyException e) {
        List<ValidationError> lve = new ArrayList<ValidationError>();
        lve.add(new ValidationError(ValidationConstants.ERROR_METADATA_PROPERTY_MISSING, e.getMessage()));
        return lve;
    } catch (XmpUnknownValueTypeException e) {
        List<ValidationError> lve = new ArrayList<ValidationError>();
        lve.add(new ValidationError(ValidationConstants.ERROR_METADATA_UNKNOWN_VALUETYPE, e.getMessage()));
        return lve;
    } catch (XmpParsingException e) {
        List<ValidationError> lve = new ArrayList<ValidationError>();
        lve.add(new ValidationError(ValidationConstants.ERROR_METADATA_FORMAT, e.getMessage()));
        return lve;
    }

    catch (IOException e) {
        throw new ValidationException("Failed while validating", e);
    }
}

From source file:net.padaf.preflight.helpers.StreamValidationHelper.java

License:Apache License

@Override
public List<ValidationError> innerValidate(DocumentHandler handler) throws ValidationException {
    List<ValidationError> result = new ArrayList<ValidationError>(0);
    PDDocument pdfDoc = handler.getDocument();
    COSDocument cDoc = pdfDoc.getDocument();

    List<?> lCOSObj = cDoc.getObjects();
    for (Object o : lCOSObj) {
        COSObject cObj = (COSObject) o;//from w ww  . j av a 2 s.  co  m

        // If this object represents a Stream, the Dictionary must contain the
        // Length key
        COSBase cBase = cObj.getObject();
        if (cBase instanceof COSStream) {
            // it is a stream
            result.addAll(validateStreamObject(handler, cObj));
        }
    }
    return result;
}