List of usage examples for org.apache.pdfbox.pdmodel PDDocumentCatalog getAcroForm
public PDAcroForm getAcroForm()
From source file:FormFiller.java
private static void fillPdf(HashMap dealerTrackData, String inputFileName, String outputDir, String outputFormType) {//from w w w. j a va 2s. c o m try { PDDocument pdfTemplate = PDDocument.load(new File(inputFileName)); PDDocumentCatalog docCatalog = pdfTemplate.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); List<PDField> fieldList = acroForm.getFields(); String[] fieldArray = new String[fieldList.size()]; int i = 0; for (PDField sField : fieldList) { fieldArray[i] = sField.getFullyQualifiedName(); i++; } for (String f : fieldArray) { PDField field = acroForm.getField(f); String value = (String) dealerTrackData.get(f); if (value != null) { try { field.setValue(value); } catch (IllegalArgumentException e) { System.err.println("Could not insert: " + f + "."); } } } pdfTemplate.save(outputDir + "/" + dealerTrackData.get("fullName") + " " + outputFormType + ".pdf"); // printing - need to look into the long form stuff! if (print && !inputFileName.contains("Title Guarantee")) printPdf(pdfTemplate, dealerTrackData, inputFileName, inputFileName.contains("Purchase Contract") ? 2 : 1); pdfTemplate.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:SetField.java
License:Apache License
/** * This will set a single field in the document. * * @param pdfDocument The PDF to set the field in. * @param name The name of the field to set. * @param value The new value of the field. * * @throws IOException If there is an error setting the field. *//*from w ww .j av a2 s.co m*/ public void setField(PDDocument pdfDocument, String[] args) throws IOException { PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); for (int i = 0; i < args.length - 1; i = i + 2) { PDField field = acroForm.getField(args[i]); if (field != null) { field.setValue(args[i + 1]); } else { System.err.println("No field found with name:" + args[i]); } } }
From source file:ch.vaudoise.vaapi.dctm.resource.root.LoadAndSetPDF.java
public static void setPDF(String nom, String prenom, String adresse, String telephone, String commentaire, String description) throws IOException { String adressePart1 = null;//from w w w . j av a 2s. c o m String adressePart2 = null; String[] adresseTab = adressParser(adresse); if (adresseTab.length > 0) { adressePart1 = (adresseTab[0] + " " + adresseTab[1]); adressePart2 = (adresseTab[2] + " " + adresseTab[3]); } //Loading an existing document File file = new File("C:\\Temp\\declaration.pdf"); try (PDDocument document = PDDocument.load(file)) { PDDocumentCatalog docCatalog = document.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); // Get field names List<PDField> fieldList = acroForm.getFields(); // String the object array String[] fieldArray = new String[fieldList.size()]; int i = 0; for (PDField sField : fieldList) { fieldArray[i] = sField.getFullyQualifiedName(); i++; } // Loop through each field in the array and fill the blanks for (String f : fieldArray) { PDField field = acroForm.getField(f); // System.out.println(f); switch (f) { case "Nom prnom ou raison sociale": { if (nom != null && nom != null) { field.setValue(nom + " " + prenom); break; } else { field.setValue("Faten"); break; } } case "Adresse": { if (adressePart1 != null) { field.setValue(adressePart1); break; } else { field.setValue("Rue des moulins 12"); break; } } case "NPA et localit": { if (adressePart2 != null) { field.setValue(adressePart2); break; } else { field.setValue("1006 lausanne"); break; } } case "Tlphone et et fax": { if (telephone != null) { field.setValue(telephone); break; } else { field.setValue(""); break; } } case "Email": { field.setValue(""); break; } case "Nom de la personne de contact": { field.setValue(nom + " " + prenom); break; } case "CCP ou compte bancaire": { field.setValue(""); break; } case "Si oui N TVA": { field.setValue(""); break; } case "Si oui compagnie": { field.setValue(""); break; } case "Numro de contrat dassurance ex1234562200": { field.setValue("1234564100"); break; } case "Remarques": { if (commentaire != null) { field.setValue(commentaire); break; } else { field.setValue("Rien signaler ..."); break; } } case "Description de": { if (description != null) { field.setValue(description); break; } else { field.setValue("Rien signaler ..."); break; } } } } //Saving the document document.save("C:/temp/declarationRemplie.pdf"); //Closing the document document.close(); } }
From source file:com.fangxin365.core.utils.PDFMerger.java
License:Apache License
/** * append all pages from source to destination. * /* w ww . ja v a 2s. c o m*/ * @param destination * the document to receive the pages * @param source * the document originating the new pages * * @throws IOException * If there is an error accessing data from either document. */ public void appendDocument(PDDocument destination, PDDocument source) throws IOException { if (destination.isEncrypted()) { System.out.println("Error: destination PDF is encrypted, can't append encrypted PDF documents."); } if (source.isEncrypted()) { System.out.println("Error: source PDF is encrypted, can't append encrypted PDF documents."); } PDDocumentInformation destInfo = destination.getDocumentInformation(); PDDocumentInformation srcInfo = source.getDocumentInformation(); destInfo.getDictionary().mergeInto(srcInfo.getDictionary()); PDDocumentCatalog destCatalog = destination.getDocumentCatalog(); PDDocumentCatalog srcCatalog = source.getDocumentCatalog(); // use the highest version number for the resulting pdf float destVersion = destination.getDocument().getVersion(); float srcVersion = source.getDocument().getVersion(); if (destVersion < srcVersion) { destination.getDocument().setVersion(srcVersion); } if (destCatalog.getOpenAction() == null) { destCatalog.setOpenAction(srcCatalog.getOpenAction()); } // maybe there are some shared resources for all pages COSDictionary srcPages = (COSDictionary) srcCatalog.getCOSDictionary().getDictionaryObject(COSName.PAGES); COSDictionary srcResources = (COSDictionary) srcPages.getDictionaryObject(COSName.RESOURCES); COSDictionary destPages = (COSDictionary) destCatalog.getCOSDictionary().getDictionaryObject(COSName.PAGES); COSDictionary destResources = (COSDictionary) destPages.getDictionaryObject(COSName.RESOURCES); if (srcResources != null) { if (destResources != null) { destResources.mergeInto(srcResources); } else { destPages.setItem(COSName.RESOURCES, srcResources); } } PDFCloneUtility cloner = new PDFCloneUtility(destination); try { PDAcroForm destAcroForm = destCatalog.getAcroForm(); PDAcroForm srcAcroForm = srcCatalog.getAcroForm(); if (destAcroForm == null) { cloner.cloneForNewDocument(srcAcroForm); destCatalog.setAcroForm(srcAcroForm); } else { if (srcAcroForm != null) { mergeAcroForm(cloner, destAcroForm, srcAcroForm); } } } catch (Exception e) { // if we are not ignoring exceptions, we'll re-throw this if (!ignoreAcroFormErrors) { throw (IOException) e; } } COSArray destThreads = (COSArray) destCatalog.getCOSDictionary().getDictionaryObject(COSName.THREADS); COSArray srcThreads = (COSArray) cloner .cloneForNewDocument(destCatalog.getCOSDictionary().getDictionaryObject(COSName.THREADS)); if (destThreads == null) { destCatalog.getCOSDictionary().setItem(COSName.THREADS, srcThreads); } else { destThreads.addAll(srcThreads); } PDDocumentNameDictionary destNames = destCatalog.getNames(); PDDocumentNameDictionary srcNames = srcCatalog.getNames(); if (srcNames != null) { if (destNames == null) { destCatalog.getCOSDictionary().setItem(COSName.NAMES, cloner.cloneForNewDocument(srcNames)); } else { cloner.cloneMerge(srcNames, destNames); } } PDDocumentOutline destOutline = destCatalog.getDocumentOutline(); PDDocumentOutline srcOutline = srcCatalog.getDocumentOutline(); if (srcOutline != null) { if (destOutline == null) { PDDocumentOutline cloned = new PDDocumentOutline( (COSDictionary) cloner.cloneForNewDocument(srcOutline)); destCatalog.setDocumentOutline(cloned); } else { PDOutlineItem first = srcOutline.getFirstChild(); if (first != null) { PDOutlineItem clonedFirst = new PDOutlineItem( (COSDictionary) cloner.cloneForNewDocument(first)); destOutline.appendChild(clonedFirst); } } } String destPageMode = destCatalog.getPageMode(); String srcPageMode = srcCatalog.getPageMode(); if (destPageMode == null) { destCatalog.setPageMode(srcPageMode); } COSDictionary destLabels = (COSDictionary) destCatalog.getCOSDictionary() .getDictionaryObject(COSName.PAGE_LABELS); COSDictionary srcLabels = (COSDictionary) srcCatalog.getCOSDictionary() .getDictionaryObject(COSName.PAGE_LABELS); if (srcLabels != null) { int destPageCount = destination.getNumberOfPages(); COSArray destNums = null; if (destLabels == null) { destLabels = new COSDictionary(); destNums = new COSArray(); destLabels.setItem(COSName.NUMS, destNums); destCatalog.getCOSDictionary().setItem(COSName.PAGE_LABELS, destLabels); } else { destNums = (COSArray) destLabels.getDictionaryObject(COSName.NUMS); } COSArray srcNums = (COSArray) srcLabels.getDictionaryObject(COSName.NUMS); if (srcNums != null) { for (int i = 0; i < srcNums.size(); i += 2) { COSNumber labelIndex = (COSNumber) srcNums.getObject(i); long labelIndexValue = labelIndex.intValue(); destNums.add(COSInteger.get(labelIndexValue + destPageCount)); destNums.add(cloner.cloneForNewDocument(srcNums.getObject(i + 1))); } } } COSStream destMetadata = (COSStream) destCatalog.getCOSDictionary().getDictionaryObject(COSName.METADATA); COSStream srcMetadata = (COSStream) srcCatalog.getCOSDictionary().getDictionaryObject(COSName.METADATA); if (destMetadata == null && srcMetadata != null) { PDStream newStream = new PDStream(destination, srcMetadata.getUnfilteredStream(), false); newStream.getStream().mergeInto(srcMetadata); newStream.addCompression(); destCatalog.getCOSDictionary().setItem(COSName.METADATA, newStream); } // finally append the pages @SuppressWarnings("unchecked") List<PDPage> pages = srcCatalog.getAllPages(); Iterator<PDPage> pageIter = pages.iterator(); while (pageIter.hasNext()) { PDPage page = pageIter.next(); PDPage newPage = new PDPage((COSDictionary) cloner.cloneForNewDocument(page.getCOSDictionary())); newPage.setCropBox(page.findCropBox()); newPage.setMediaBox(page.findMediaBox()); newPage.setRotation(page.findRotation()); destination.addPage(newPage); } }
From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java
License:Apache License
/** * Do Partial PDF Save. This save works when updating Signature fields. * @param docBytes byte[]/*from w w w . j av a 2 s . c o m*/ * @param archive {@link ArchiveDTO} * @param output {@link WorkflowOutputPdfForm} * @throws IOException IOException */ private void doSignaturePdfSave(final byte[] docBytes, final ArchiveDTO archive, final WorkflowOutputPdfForm output) throws IOException { boolean signed = false; List<SignatureOptions> signatureOptions = new ArrayList<>(); PDDocument doc = loadPDF(docBytes); try { PDDocumentCatalog docCatalog = doc.getDocumentCatalog(); PDAcroForm pdform = docCatalog.getAcroForm(); for (WorkflowOutputFormField ofield : output.getFields()) { Optional<FormJSON> form = findForm(archive, ofield); Optional<FormJSONField> field = findFormField(form, ofield); if (form.isPresent() && field.isPresent()) { String value = field.get().getValue(); PDField pfield = pdform.getField(ofield.getDocumentfieldname()); if (pfield != null && pfield instanceof PDSignatureField) { byte[] bs = form.get().getAssetData().get(value); if (bs != null) { try { InputStream is = new ByteArrayInputStream(bs); signatureOptions.add(setValue(doc, (PDSignatureField) pfield, is)); signed = true; } catch (IllegalStateException e) { LOG.log(Level.WARNING, "unable to set signature", e); } } } } } if (signed) { ByteArrayOutputStream bs = new ByteArrayOutputStream(); doc.saveIncremental(bs); bs.close(); String pdfname = output.getName(); archive.addPDF(pdfname + ".pdf", bs.toByteArray()); } for (SignatureOptions sigOption : signatureOptions) { IOUtils.closeQuietly(sigOption); } } finally { doc.close(); } }
From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java
License:Apache License
/** * Do Full PDF Save. This save works when updating the values of fields. * @param docBytes byte[]//ww w .j a v a 2 s . com * @param archive {@link ArchiveDTO} * @param output {@link WorkflowOutputPdfForm} * @return boolean - whether signature fields are found * @throws IOException IOException */ private boolean dofullPDFSave(final byte[] docBytes, final ArchiveDTO archive, final WorkflowOutputPdfForm output) throws IOException { boolean hasSignatures = false; PDDocument doc = loadPDF(docBytes); try { PDDocumentCatalog docCatalog = doc.getDocumentCatalog(); PDAcroForm pdform = docCatalog.getAcroForm(); for (WorkflowOutputFormField ofield : output.getFields()) { Optional<FormJSON> form = findForm(archive, ofield); Optional<FormJSONField> field = findFormField(form, ofield); if (form.isPresent() && field.isPresent()) { PDField pdfield = pdform.getField(ofield.getDocumentfieldname()); if (pdfield != null) { if (pdfield instanceof PDSignatureField) { hasSignatures = true; } else { String value = field.get().getValue(); List<String> values = field.get().getValues(); if (!isEmpty(values)) { for (String val : values) { pdfield.setValue(extractLabelAndValue(val).getRight()); } } else if (!isEmpty(value)) { value = extractLabelAndValue(value).getRight(); pdfield.setValue(value); } } } } } ByteArrayOutputStream bs = new ByteArrayOutputStream(); doc.save(bs); bs.close(); String pdfname = output.getName(); archive.addPDF(pdfname + ".pdf", bs.toByteArray()); return hasSignatures; } finally { doc.close(); } }
From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java
License:Apache License
/** * Take {@link PDField} objects from {@link PDDocument} * and create {@link PDField} from them. * * @param doc {@link PDDocument}/*from ww w . j a v a 2 s . c om*/ * @param objMap {@link Map} of {@link COSDictionary} and Page Number * @return {@link Map} of {@link PDField} by page number * @throws IOException IOException */ private Map<Integer, List<PDField>> getPDFields(final PDDocument doc, final Map<COSDictionary, Integer> objMap) throws IOException { PDDocumentCatalog dc = doc.getDocumentCatalog(); PDAcroForm pdform = dc.getAcroForm(); Map<Integer, List<PDField>> map = new HashMap<>(); for (PDField field : pdform.getFields()) { if (field instanceof PDPushButton) { LOG.log(Level.FINE, "skip addFieldToPageMap='" + field.getFullyQualifiedName() + "',class=" + field.getClass().getName()); continue; } addFieldToPageMap(objMap, field, map); } for (Map.Entry<Integer, List<PDField>> e : map.entrySet()) { Collections.sort(e.getValue(), new PDFieldComparator()); } return map; }
From source file:com.mycompany.mavenproject1.ragaiproject.PDFManipulation.java
public String[] getFieldNames(PDDocument pdfDocument, JList list) { int i = 0;//from w ww .j a v a 2s .co m String[] names = new String[10000]; PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); java.util.List<PDField> fields = acroForm.getFields(); for (PDField field : fields) { names[i] = field.getPartialName(); this.arrayOfFieldNames[i] = names[i]; list.setListData(names); this.fieldLabelPairs.add(new Pair(field.getPartialName(), field.getValueAsString())); System.out.println(this.fieldLabelPairs.size()); i++; } return names; }
From source file:com.mycompany.mavenproject1.ragaiproject.PDFManipulation.java
public void convert(List<PDDocument> pdfList, List<String> selectedFields, String fileName) { Workbook wb = new HSSFWorkbook(); CreationHelper createHelper = wb.getCreationHelper(); HSSFSheet s1 = (HSSFSheet) wb.createSheet("Sheet 1"); Row header = s1.createRow((short) 0); //initialize column headers for (int i = 0; i < selectedFields.size(); i++) { Cell headerCell = header.createCell(i); headerCell.setCellValue(selectedFields.get(i)); }//from w w w . ja va2s . c o m //for(int i = 0; i < selectedFields.size();i++){ //fills out row //Cell dataCell = data.createCell(i); for (int y = 0; y < pdfList.size(); y++) { PDDocumentCatalog docCatalog = pdfList.get(y).getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); java.util.List<PDField> fields = acroForm.getFields(); Row data = s1.createRow((short) y + 1); for (int i = 0; i < selectedFields.size(); i++) { Cell dataCell = data.createCell(i); for (PDField field : fields) { System.out.println("Field Value: " + field.getValueAsString()); if (field.getPartialName().equals(selectedFields.get(i))) { dataCell.setCellValue(field.getValueAsString()); } } } /* for(int j = 0; j < this.fieldLabelPairs.size();j++){ if(this.fieldLabelPairs.get(j).getLabel().equals(selectedFields.get(i))){ dataCell.setCellValue(this.fieldLabelPairs.get(j).getValue()); } }*/ } //} /*for (int i = 0; i < selectedFields.size(); i++){ Row data = s1.createRow(i+1); for(int j = 0; j< this.fieldLabelPairs.length; j++){ Cell dataCell = data.createCell(i); if(this.fieldLabelPairs[j].getLabel().equals(selectedFields.get(i))){ dataCell.setCellValue(this.fieldLabelPairs[j].getValue()); } } }*/ FileOutputStream fileOut = null; try { fileOut = new FileOutputStream(fileName + ".xls"); try { wb.write(fileOut); fileOut.close(); } catch (IOException ex) { Logger.getLogger(ExcelExport.class.getName()).log(Level.SEVERE, null, ex); } } catch (FileNotFoundException ex) { Logger.getLogger(ExcelExport.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:cr.ac.siua.tec.utils.impl.AssistancePDFGenerator.java
License:Open Source License
/** * Fills the PDF file (asistente.pdf) with the ticket values and returns base64 encoded string. *//*from w w w. jav a 2s. c o m*/ @Override public String generate(HashMap<String, String> formValues) { String originalPdf = PDFGenerator.RESOURCES_PATH + "asistente.pdf"; try { PDDocument _pdfDocument = PDDocument.load(originalPdf); PDDocumentCatalog docCatalog = _pdfDocument.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); //Set some fields manually. Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1; if (month > 10 || month < 5) acroForm.getField("Semestre").setValue("PRIMER"); else acroForm.getField("Semestre").setValue("SEGUNDO"); if (month > 10 && acroForm.getField("Semestre").getValue().equals("PRIMER")) year++; acroForm.getField("Ao").setValue(String.valueOf(year)); formValues.remove("Queue"); acroForm.getField(formValues.get("Banco")).setValue("x"); formValues.remove("Banco"); acroForm.getField(formValues.get("Tipo de asistencia")).setValue("x"); formValues.remove("Tipo de asistencia"); //Iterates through remaining custom fields. for (Map.Entry<String, String> entry : formValues.entrySet()) { acroForm.getField(entry.getKey()).setValue(entry.getValue()); } return encodePDF(_pdfDocument); } catch (IOException e) { e.printStackTrace(); System.out.println("Excepcin al llenar el PDF."); return null; } }