public string PdfFields() { string pdfText = String.Empty; PDFParser parser = new PDFParser(new BufferedInputStream(new FileInputStream(PdfFile))); parser.parse(); PDDocument originialPdfDoc = parser.getPDDocument(); bool isOriginalDocEncrypted = originialPdfDoc.isEncrypted(); if (isOriginalDocEncrypted) { originialPdfDoc.openProtection(new StandardDecryptionMaterial(PdfPassword)); } try { PDDocumentCatalog docCatalog = originialPdfDoc.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); PDField field = acroForm.getField("Name"); if (field != null) { field.setValue("name"); } } catch (java.io.IOException ex) { throw ex; } return(pdfText); }
public void SetXMPMetadata(XmlDocument xmp) { string outerXml = xmp.OuterXml; InputStream byteArrayInputStream = new ByteArrayInputStream(Encoding.UTF8.GetBytes(outerXml)); PDDocumentCatalog documentCatalog = this.pdfDocument.getDocumentCatalog(); documentCatalog.setMetadata(new PDMetadata(this.pdfDocument, byteArrayInputStream)); }
public void SplitByTopLevelBookmarks() { if (this.CheckOutput()) { PDFHelper.DisplayTrialPopupIfNecessary(); try { PDDocumentCatalog documentCatalog = this.pdfDocument.PDFBoxDocument.getDocumentCatalog(); PDDocumentOutline documentOutline = documentCatalog.getDocumentOutline(); if (documentOutline != null) { PDOutlineItem firstChild = documentOutline.getFirstChild(); PDPageTree pages = documentCatalog.getPages(); List <int> nums = new List <int>(); while (firstChild != null) { PDPage pDPage = firstChild.findDestinationPage(this.pdfDocument.PDFBoxDocument); nums.Add(pages.indexOf(pDPage)); firstChild = firstChild.getNextSibling(); } nums.Add(pages.getCount()); for (int i = 0; i < nums.Count - 1; i++) { int item = nums[i]; int num = nums[i + 1]; PDDocument pDDocument = new PDDocument(); for (int j = item; j < num; j++) { pDDocument.addPage(this.pdfDocument.PDFBoxDocument.getPage(j)); } pDDocument = PDFHelper.AddTrialStampIfNecessary(pDDocument); string str = string.Format("{0} [{1}].pdf", this.OutputFileName, i); pDDocument.save(Path.Combine(this.OutputFilePath, str)); pDDocument.close(); } } else { Console.WriteLine("This document does not contain any bookmarks."); } } catch (Exception exception1) { Exception exception = exception1; throw new PDFToolkitException(exception.Message, exception.InnerException); } } }
public PDFDocumentOpenSetting(PDFDocument pdfDoc) { this.documentDocumentOpenSettings = pdfDoc.PDFBoxDocument.getDocumentCatalog(); this.pdfDocument = pdfDoc; if (this.documentDocumentOpenSettings != null) { if (this.documentDocumentOpenSettings.getViewerPreferences() != null) { this.documentViewerPrefernces = this.documentDocumentOpenSettings.getViewerPreferences(); } else { this.documentViewerPrefernces = new PDViewerPreferences(new COSDictionary()); } } }
private void DeleteFile_Click(object sender, RoutedEventArgs e) { // to delete we just mark for not to be reincluded and do a round of saving PDDocumentCatalog catalog = pd.getDocumentCatalog(); PDDocumentNameDictionary names = catalog.getNames(); PDEmbeddedFilesNameTreeNode embeddedFiles = names.getEmbeddedFiles(); Map embeddedFileNames = embeddedFiles.getNames(); Dictionary <String, PDComplexFileSpecification> embeddedFileNamesNet = embeddedFileNames.ToDictionary <String, PDComplexFileSpecification>(); Map TomsNewMap = new HashMap(); // Attach all the existing files foreach (KeyValuePair <String, PDComplexFileSpecification> entry in embeddedFileNamesNet) { if (selectedFile == entry.Key) { // } else { TomsNewMap.put(entry.Key, entry.Value); } } PDEmbeddedFilesNameTreeNode TomsEmbeddedFiles = new PDEmbeddedFilesNameTreeNode(); TomsEmbeddedFiles.setNames(TomsNewMap); names.setEmbeddedFiles(TomsEmbeddedFiles); catalog.setNames(names); pd.save(pathToCurrentPDF); // reload the PDF LoadPDFAndLookForAttachments(pathToCurrentPDF); ButtonsStackPanel.Visibility = Visibility.Hidden; }
private void DoMetadata() { java.util.TimeZone timeZone = java.util.TimeZone.getTimeZone("GMT"); Calendar instance = Calendar.getInstance(); instance.setTimeZone(timeZone); PDDocumentInformation documentInformation = this.doc.getDocumentInformation(); documentInformation.setModificationDate(instance); if (documentInformation.getAuthor() == null) { documentInformation.setAuthor("Aquaforest"); } if ((string.IsNullOrEmpty(documentInformation.getProducer()) ? true : documentInformation.getProducer() == " ")) { documentInformation.setProducer("Aquaforest PDFA - http://www.aquaforest.com"); } if (documentInformation.getKeywords() == null) { documentInformation.setKeywords(""); } documentInformation.getCreationDate(); instance.setTime(this.GetDate(documentInformation.getCreationDate())); documentInformation.setCreationDate(instance); this.doc.setDocumentInformation(documentInformation); this.doc.save(this.tempFileName); documentInformation = this.doc.getDocumentInformation(); PDDocumentCatalog documentCatalog = this.doc.getDocumentCatalog(); XMPMetadata xMPMetadatum = XMPMetadata.createXMPMetadata(); if (this.ConformanceLevel.Trim().ToLower() == "a") { PDMarkInfo pDMarkInfo = new PDMarkInfo(); pDMarkInfo.setMarked(true); documentCatalog.setMarkInfo(pDMarkInfo); } PDFAIdentificationSchema pDFAIdentificationSchema = xMPMetadatum.createAndAddPFAIdentificationSchema(); pDFAIdentificationSchema.setConformance(this.ConformanceLevel); pDFAIdentificationSchema.setPart(new Integer(this.pdfaversion)); DublinCoreSchema dublinCoreSchema = xMPMetadatum.createAndAddDublinCoreSchema(); string title = documentInformation.getTitle(); if (title != null) { dublinCoreSchema.setTitle(title); } title = documentInformation.getSubject(); if (title != null) { dublinCoreSchema.setDescription(title); } title = documentInformation.getAuthor(); if (title != null) { dublinCoreSchema.addCreator(title); } AdobePDFSchema adobePDFSchema = xMPMetadatum.createAndAddAdobePDFSchema(); title = documentInformation.getProducer(); if (title != null) { adobePDFSchema.setProducer(title); } title = documentInformation.getKeywords(); if (title != null) { adobePDFSchema.setKeywords(title); } XMPBasicSchema xMPBasicSchema = xMPMetadatum.createAndAddXMPBasicSchema(); title = documentInformation.getCreator(); if (title != null) { xMPBasicSchema.setCreatorTool(title); } if (documentInformation.getCreationDate() != null) { xMPBasicSchema.setCreateDate(documentInformation.getCreationDate()); } if (documentInformation.getModificationDate() != null) { xMPBasicSchema.setModifyDate(documentInformation.getModificationDate()); } xMPBasicSchema.setMetadataDate(new GregorianCalendar()); XmpSerializer xmpSerializer = new XmpSerializer(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); SAXParserFactoryImpl sAXParserFactoryImpl = new SAXParserFactoryImpl(); TransformerFactoryImpl transformerFactoryImpl = new TransformerFactoryImpl(); xmpSerializer.serialize(xMPMetadatum, byteArrayOutputStream, false); PDMetadata pDMetadatum = new PDMetadata(this.doc); pDMetadatum.importXMPMetadata(byteArrayOutputStream.toByteArray()); documentCatalog.setMetadata(pDMetadatum); this.doc.save(this.tempFileName); documentInformation = this.doc.getDocumentInformation(); }
public PDFAValidationResult ConvertToPDFA() { PDFAValidationResult pDFAValidationResult = new PDFAValidationResult(); try { try { bool flag = true; this.CheckImages(); pDFAValidationResult.IsValid = false; this.EmbedFonts(flag); this.doc.save(this.tempFileName); PDDocumentCatalog documentCatalog = this.doc.getDocumentCatalog(); try { if (documentCatalog.getOutputIntents().size() <= 0) { this.colorProfile = new FileInputStream(this.iccString); PDOutputIntent pDOutputIntent = new PDOutputIntent(this.doc, this.colorProfile); pDOutputIntent.setInfo("sRGB IEC61966-2.1"); pDOutputIntent.setOutputCondition("sRGB IEC61966-2.1"); pDOutputIntent.setOutputConditionIdentifier("sRGB IEC61966-2.1"); pDOutputIntent.setRegistryName("http://www.color.org"); documentCatalog.addOutputIntent(pDOutputIntent); this.doc.save(this.tempFileName); } } catch (Exception exception) { } PDFHelper.DisplayTrialPopupIfNecessary(); PDFHelper.AddTrialStampIfNecessary(this.doc, false); this.DoMetadata(); if (!this.ValidatePDF) { Console.WriteLine("The file was convereted but it has not been validated, to validate pdfa files after conversion set the ValidatePDF porperty to true."); System.IO.File.Copy(this.tempFileName, this.outPutFileName, this.overwrite); } else { PDFAValidationResult pDFAValidationResult1 = (new PDFAValidator()).ValidatePDFA(this.tempFileName, (AquaforestPDFAFlavour)this.PDFAFlavour); pDFAValidationResult.IsValid = pDFAValidationResult1.IsValid; pDFAValidationResult.ValidationResult = pDFAValidationResult1.ValidationResult; if ((pDFAValidationResult.IsValid ? false : !this.copyUnvalidated)) { Console.WriteLine("The file was convereted but failed during validation. If you want to copy this to the output file set CopyUnvalidated to true"); } else { System.IO.File.Copy(this.tempFileName, this.outPutFileName, this.overwrite); } } } catch (Exception exception1) { Console.WriteLine("The attempted pdf/a conversion failed.\n{0}", exception1.Message); PDF2PDFaConverter.EmptyDirectory(Path.GetDirectoryName(this.tempFileName)); Directory.Delete(Path.GetDirectoryName(this.tempFileName)); } } finally { if (this.doc != null) { this.doc.close(); this.doc = null; } try { PDF2PDFaConverter.EmptyDirectory(Path.GetDirectoryName(this.tempFileName)); Directory.Delete(Path.GetDirectoryName(this.tempFileName)); } catch (Exception exception2) { } } return(pDFAValidationResult); }
private void LoadPDFAndLookForAttachments(string PDFPath) { try { pd.close(); } catch { // pd isn't open } FileDropStatus.Text = ""; AttachmentsPanel.Children.Clear(); if (!String.Equals(System.IO.Path.GetExtension(PDFPath), ".pdf", StringComparison.CurrentCultureIgnoreCase)) { MessageBoxResult result = MessageBox.Show("PDF Attacher only reads PDFs.", "PDF expected."); } else { FileDropStatus.Text = System.IO.Path.GetFileName(PDFPath); pd = PDDocument.load(PDFPath); // Get attachments and save out as a file PDDocumentCatalog catalog = pd.getDocumentCatalog(); PDDocumentNameDictionary names = catalog.getNames(); PDEmbeddedFilesNameTreeNode embeddedFiles = names.getEmbeddedFiles(); Map embeddedFileNames = embeddedFiles.getNames(); embeddedFileNamesNet = embeddedFileNames.ToDictionary <String, PDComplexFileSpecification>(); AttachmentsPanel.Children.Clear(); //For-Each Loop is used to list all embedded files (if there is more than one) foreach (KeyValuePair <String, PDComplexFileSpecification> entry in embeddedFileNamesNet) { StackPanel attachmentPanel = new StackPanel(); attachmentPanel.Orientation = Orientation.Vertical; attachmentPanel.Margin = new Thickness(5); attachmentPanel.MinWidth = 90; System.Windows.Controls.Image attachmentImage = new System.Windows.Controls.Image(); attachmentImage.Height = 32; attachmentImage.Width = 32; attachmentPanel.Tag = entry.Key; attachmentPanel.MouseEnter += AttachmentPanel_MouseEnter; attachmentPanel.MouseLeave += AttachmentPanel_MouseLeave; attachmentPanel.MouseUp += AttachmentPanel_MouseUp; Icon attachmentIcon = ShellIcon.GetLargeIconFromExtension(System.IO.Path.GetExtension(entry.Key)); BitmapSource attachmentBitmapSource = Imaging.CreateBitmapSourceFromHIcon(attachmentIcon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); attachmentImage.Source = attachmentBitmapSource; attachmentImage.Margin = new Thickness(5, 5, 5, 0); attachmentIcon.Dispose(); TextBlock attachmentTextBlock = new TextBlock(); attachmentTextBlock.Margin = new Thickness(5); attachmentTextBlock.Text = System.IO.Path.GetFileName(entry.Key); System.Windows.Controls.Image deleteImage = new System.Windows.Controls.Image(); deleteImage.Height = 20; deleteImage.Width = 20; deleteImage.Margin = new Thickness(0, 6, -50, -6); // var uriSource = new Uri(@"/PDFBox_sharp;component/DeleteIcon.png", UriKind.Relative); // deleteImage.Source = new BitmapImage(uriSource); // attachmentPanel.Children.Add(deleteImage); attachmentPanel.Children.Add(attachmentImage); attachmentPanel.Children.Add(attachmentTextBlock); AttachmentsPanel.Children.Add(attachmentPanel); } Icon sysicon = System.Drawing.Icon.ExtractAssociatedIcon(PDFPath); BitmapSource bmpSrc = Imaging.CreateBitmapSourceFromHIcon(sysicon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); PDFIcon.Source = bmpSrc; sysicon.Dispose(); } //pd.close(); }
// Decent example here -- https://github.com/Aiybe/PDFData/blob/master/od-reader/src/main/java/im/abe/pdfdata/AttachmentDataStorage.java private void AttachmentZone_Drop(object sender, DragEventArgs e) { // reset UI AttachmentZoneBorder.BorderThickness = new Thickness(1); AttachmentZone.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 255, 255)); deselectAllAttachmentPanels(); // attach files to PDF if (e.Data.GetDataPresent(DataFormats.FileDrop)) { // Note that you can have more than one file. string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); List <string> filesList = files.ToList(); if (pd != null) { foreach (string file in filesList) { byte[] fileBytes; try { fileBytes = System.IO.File.ReadAllBytes(file); } catch { // couldn't read file MessageBox.Show("Can't open " + file + " make sure it is not open in another application.", "Can't open file."); continue; } FileStream _filestream = System.IO.File.Open(file, FileMode.Open); string nameOfFileToAttach = _filestream.Name; _filestream.Close(); PDComplexFileSpecification fs = new PDComplexFileSpecification(); fs.setFile(nameOfFileToAttach); ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes, 0, fileBytes.Length); //ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes); PDEmbeddedFile embeddedFile = new PDEmbeddedFile(pd, inputStream); embeddedFile.setModDate(java.util.Calendar.getInstance()); embeddedFile.setSize(fileBytes.Length); fs.setEmbeddedFile(embeddedFile); PDDocumentCatalog catalog = pd.getDocumentCatalog(); PDDocumentNameDictionary names = catalog.getNames(); Map TomsNewMap = new HashMap(); if (names != null) { // there are already some attached files PDEmbeddedFilesNameTreeNode embeddedFiles = names.getEmbeddedFiles(); Map embeddedFileNames = embeddedFiles.getNames(); Dictionary <String, PDComplexFileSpecification> embeddedFileNamesNet = embeddedFileNames.ToDictionary <String, PDComplexFileSpecification>(); // Attach all the existing files foreach (KeyValuePair <String, PDComplexFileSpecification> entry in embeddedFileNamesNet) { TomsNewMap.put(entry.Key, entry.Value); } } else { // there are no files already attached -- so create a new name dictionary names = new PDDocumentNameDictionary(catalog); } // Attach the new file TomsNewMap.put(System.IO.Path.GetFileName(nameOfFileToAttach), fs); PDEmbeddedFilesNameTreeNode TomsEmbeddedFiles = new PDEmbeddedFilesNameTreeNode(); TomsEmbeddedFiles.setNames(TomsNewMap); names.setEmbeddedFiles(TomsEmbeddedFiles); catalog.setNames(names); pd.save(pathToCurrentPDF); pd.close(); } } else { MessageBoxResult result = MessageBox.Show("No PDF file loaded."); } } // reload the PDF LoadPDFAndLookForAttachments(pathToCurrentPDF); }
private PDDocumentCatalog makeDocPDFA3compliant(String producer, String creator, bool attachZugferdHeaders) { String fullProducer = producer + " (via mustangproject.org " + versionStr + ")"; PDDocumentCatalog cat = doc.getDocumentCatalog(); PDMetadata metadata = new PDMetadata(doc); cat.setMetadata(metadata); // we're using the jempbox org.apache.jempbox.xmp.XMPMetadata version, // not the xmpbox one XMPMetadata xmp = new XMPMetadata(); XMPSchemaPDFAId pdfaid = new XMPSchemaPDFAId(xmp); pdfaid.setAbout(""); //$NON-NLS-1$ xmp.addSchema(pdfaid); XMPSchemaDublinCore dc = xmp.addDublinCoreSchema(); dc.addCreator(creator); dc.setAbout(""); //$NON-NLS-1$ XMPSchemaBasic xsb = xmp.addBasicSchema(); xsb.setAbout(""); //$NON-NLS-1$ xsb.setCreatorTool(creator); xsb.setCreateDate(GregorianCalendar.getInstance()); // PDDocumentInformation pdi=doc.getDocumentInformation(); PDDocumentInformation pdi = new PDDocumentInformation(); pdi.setProducer(fullProducer); pdi.setAuthor(creator); doc.setDocumentInformation(pdi); XMPSchemaPDF pdf = xmp.addPDFSchema(); pdf.setProducer(fullProducer); pdf.setAbout(""); //$NON-NLS-1$ /* * // Mandatory: PDF/A3-a is tagged PDF which has to be expressed using * a // MarkInfo dictionary (PDF A/3 Standard sec. 6.7.2.2) PDMarkInfo * markinfo = new PDMarkInfo(); markinfo.setMarked(true); * doc.getDocumentCatalog().setMarkInfo(markinfo); */ /* * * To be on the safe side, we use level B without Markinfo because we * can not guarantee that the user correctly tagged the templates for * the PDF. */ pdfaid.setConformance(conformanceLevel);//$NON-NLS-1$ //$NON-NLS-1$ pdfaid.setPart(new java.lang.Integer(3)); if (attachZugferdHeaders) { addZugferdXMP(xmp); /* * this is the only line where we do something * Zugferd-specific, i.e. add PDF metadata * specifically for Zugferd, not generically for * a embedded file */ } metadata.importXMPMetadata(xmp); return(cat); }