public static void Main() { // NOTE: // When used in trial mode, the library imposes some restrictions. // Please visit http://bitmiracle.com/pdf-library/trial-restrictions.aspx // for more information. string pathToFile = "AddAttachments.pdf"; using (PdfDocument pdf = new PdfDocument()) { // add shared attachment to the document PdfFileSpecification ammerland = pdf.CreateFileAttachment(@"Sample Data\ammerland.jpg"); pdf.SharedAttachments.Add(ammerland); // add file attachment annotation to the first page PdfRectangle bounds = new PdfRectangle(20, 70, 100, 100); PdfFileSpecification jpeg = pdf.CreateFileAttachment(@"Sample Data\jpeg.pdf"); pdf.Pages[0].AddFileAnnotation(bounds, jpeg); pdf.Save(pathToFile); } Process.Start(pathToFile); }
/* ----------------------------------------------------------------- */ /// /// Set /// /// <summary> /// Sets attachments to the specified writer. /// </summary> /// /// <param name="src">PdfCopy object.</param> /// <param name="data">Collection of attachments.</param> /// /* ----------------------------------------------------------------- */ public static void Set(this PdfCopy src, IEnumerable <Attachment> data) { var done = new List <Attachment>(); foreach (var item in data) { var dup = done.Any(e => e.Name.ToLower() == item.Name.ToLower() && e.Length == item.Length && e.Checksum.SequenceEqual(item.Checksum) ); if (dup) { continue; } var fs = item is EmbeddedAttachment? PdfFileSpecification.FileEmbedded(src, null, item.Name, item.Data) : PdfFileSpecification.FileEmbedded(src, item.Source, item.Name, null); fs.SetUnicodeFileName(item.Name, true); src.AddFileAttachment(fs); done.Add(item); } }
// --------------------------------------------------------------------------- /** * Creates a FileAttachmentEvent. * * @param writer the writer to which the file attachment has to be added. * @param fs the file specification. * @param description a description for the file attachment. */ public FileAttachmentEvent( PdfWriter writer, PdfFileSpecification fs, String description) { this.writer = writer; this.fs = fs; this.description = description; }
virtual public void FileSpecCheckTest6() { Document document = new Document(); PdfAWriter writer = PdfAWriter.GetInstance(document, new FileStream(OUT + "fileSpecCheckTest2.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_3B); writer.CreateXmpMetadata(); document.Open(); Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12); document.Add(new Paragraph("Hello World", font)); FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read); ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream); iccProfileFileStream.Close(); writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc); PdfDictionary _params = new PdfDictionary(); _params.Put(PdfName.MODDATE, new PdfDate()); PdfFileSpecification fileSpec = PdfFileSpecification.FileEmbedded( writer, RESOURCES + "foo.xml", "foo.xml", null, false, "text/xml", _params); fileSpec.Put(PdfName.AFRELATIONSHIP, AFRelationshipValue.Data); writer.AddFileAttachment(fileSpec); document.Close(); }
public static void CreatePDFA3Invoice(string pdfFilePath, string embbedFilePath, string outputPath, string colorProfilePath) { PdfReader reader = new PdfReader(pdfFilePath); MemoryStream stream = new MemoryStream(); Document doc = new Document(); PdfAWriter writer = CreatePDFAInstance(doc, reader, stream); // Create Output Intents ICC_Profile icc = ICC_Profile.GetInstance(File.ReadAllBytes(colorProfilePath)); writer.SetOutputIntents("sRGB IEC61966-2.1", "", "http://www.color.org", "sRGB IEC61966-2.1", icc); PdfArray array = new PdfArray(); writer.ExtraCatalog.Put(new PdfName("AF"), array); PdfFileSpecification contentSpec = EmbeddedAttachment(embbedFilePath, Path.GetFileName(embbedFilePath), "text/xml", new PdfName("Alternative"), writer, "XML Data"); array.Add(contentSpec.Reference); //string stringExchangeXMP = File.ReadAllText(@"..\..\Resources/EDocument_PDFAExtensionSchema.xml"); //byte[] exchangeXMP = Encoding.ASCII.GetBytes(stringExchangeXMP); //writer.XmpMetadata = exchangeXMP; //XmpWriter xmp = new XmpWriter(stream, reader.Info); //writer.XmpMetadata = stream.ToArray(); doc.Close(); reader.Close(); File.WriteAllBytes(outputPath, stream.ToArray()); }
public virtual void FileSpecCheckTest7() { FileStream inPdf = new FileStream(RESOURCES + "fileSpec.pdf", FileMode.Open); MemoryStream xml = new MemoryStream(); StreamWriter sr = new StreamWriter(xml); sr.Write("<foo><foo2>Hello world</foo2></foo>"); sr.Close(); MemoryStream output = new MemoryStream(); PdfReader reader = new PdfReader(inPdf); PdfAStamper stamper = new PdfAStamper(reader, output, PdfAConformanceLevel.PDF_A_3B); stamper.CreateXmpMetadata(); PdfDictionary embeddedFileParams = new PdfDictionary(); embeddedFileParams.Put(PdfName.MODDATE, new PdfDate()); PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(stamper.Writer, "foo", "foo", xml.ToArray(), "text/xml", embeddedFileParams, 0); fs.Put(PdfName.AFRELATIONSHIP, AFRelationshipValue.Source); stamper.AddFileAttachment("description", fs); stamper.Close(); reader.Close(); }
virtual public void FileSpecCheckTest2() { Document document = new Document(); PdfAWriter writer = PdfAWriter.GetInstance(document, new FileStream(OUT + "fileSpecCheckTest2.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_3B); writer.CreateXmpMetadata(); document.Open(); Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12); document.Add(new Paragraph("Hello World", font)); FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read); ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream); iccProfileFileStream.Close(); writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc); MemoryStream txt = new MemoryStream(); StreamWriter outp = new StreamWriter(txt); outp.Write("<foo><foo2>Hello world</foo2></foo>"); outp.Close(); PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(writer, null, "foo.xml", txt.ToArray()); fs.Put(PdfName.AFRELATIONSHIP, AFRelationshipValue.Unspecified); writer.AddFileAttachment(fs); document.Close(); }
public void Write(Stream stream) { using (Document document = new Document()) { PdfWriter writer = PdfWriter.GetInstance(document, stream); document.Open(); document.Add(new Paragraph("This document contains a collection of PDFs")); PdfIndirectReference parentFolderObjectReference = writer.PdfIndirectReference; PdfIndirectReference childFolder1ObjectReference = writer.PdfIndirectReference; PdfIndirectReference childFolder2ObjectReference = writer.PdfIndirectReference; PdfDictionary parentFolderObject = GetFolderDictionary(0); parentFolderObject.Put(new PdfName("Child"), childFolder1ObjectReference); parentFolderObject.Put(PdfName.NAME, new PdfString()); PdfDictionary childFolder1Object = GetFolderDictionary(1); childFolder1Object.Put(PdfName.NAME, new PdfString("Folder 1")); childFolder1Object.Put(PdfName.PARENT, parentFolderObjectReference); childFolder1Object.Put(PdfName.NEXT, childFolder2ObjectReference); PdfDictionary childFolder2Object = GetFolderDictionary(2); childFolder2Object.Put(PdfName.NAME, new PdfString("Folder 2")); childFolder2Object.Put(PdfName.PARENT, parentFolderObjectReference); PdfCollection collection = new PdfCollection(PdfCollection.DETAILS); PdfCollectionSchema schema = CollectionSchema(); collection.Schema = schema; collection.Sort = new PdfCollectionSort(keys); collection.Put(new PdfName("Folders"), parentFolderObjectReference); writer.Collection = collection; PdfFileSpecification fs; PdfCollectionItem item; fs = PdfFileSpecification.FileEmbedded(writer, file1Path, File1, null); item = new PdfCollectionItem(schema); item.AddItem("Type", "pdf"); fs.AddCollectionItem(item); // the description is apparently used to place the // file in a particular folder. The number between the < and > // is used to put the file in the folder that has the matching id fs.AddDescription(GetDescription(1, File1), false); writer.AddFileAttachment(fs); fs = PdfFileSpecification.FileEmbedded(writer, file2Path, File2, null); item = new PdfCollectionItem(schema); item.AddItem("Type", "pdf"); fs.AddCollectionItem(item); fs.AddDescription(GetDescription(2, File2), false); writer.AddFileAttachment(fs); writer.AddToBody(parentFolderObject, parentFolderObjectReference); writer.AddToBody(childFolder1Object, childFolder1ObjectReference); writer.AddToBody(childFolder2Object, childFolder2ObjectReference); document.Close(); } }
private void addAttachment(AttachmentFile file) { var pdfDictionary = new PdfDictionary(); pdfDictionary.Put(PdfName.MODDATE, new PdfDate(DateTime.Now)); var fs = PdfFileSpecification.FileEmbedded(_writer, string.Empty, file.FileName, file.Content, true, null, pdfDictionary); _writer.AddFileAttachment(fs); }
/** * Adds an embedded file. * (Part of the RichMediaContent.) * @param name a name for the name tree * @param fs a file specification for an embedded file. */ virtual public PdfIndirectReference AddAsset(String name, PdfFileSpecification fs) { if (assetsmap == null) { throw new IllegalPdfSyntaxException("You can't add assets to reused RichMediaContent."); } PdfIndirectReference refi = writer.AddToBody(fs).IndirectReference; assetsmap[name] = refi; return(refi); }
protected override void CheckFileSpec(PdfWriter writer, int key, Object obj1) { if (obj1 is PdfFileSpecification) { PdfFileSpecification fileSpec = (PdfFileSpecification)obj1; if (fileSpec.Contains(PdfName.EF)) { throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("embedded.files.are.not.permitted")); } } }
internal PdfMediaClipData(string file, PdfFileSpecification fs, string mimeType) { Put(PdfName.TYPE, new PdfName("MediaClip")); Put(PdfName.S, new PdfName("MCD")); Put(PdfName.N, new PdfString("Media clip for " + file)); Put(new PdfName("CT"), new PdfString(mimeType)); PdfDictionary dic = new PdfDictionary(); dic.Put(new PdfName("TF"), new PdfString("TEMPACCESS")); Put(new PdfName("P"), dic); Put(PdfName.D, fs.Reference); }
private void GenerateEAttachmentDocument(PdfAWriter writer, XmpWriter xmpWriter, EAttactment attachment) { // Use default intent if output intent of this instance was not set if (attachment.outputIntents == null) { //byte[] iccProfile = File.ReadAllBytes("/Resources/sRGB Color Space Profile.icm"); byte[] iccProfile = Properties.Resources.sRGB_Color_Space_Profile; ICC_Profile icc = ICC_Profile.GetInstance(iccProfile); writer.SetOutputIntents("sRGB IEC61966-2.1", "", "http://www.color.org", "sRGB IEC61966-2.1", icc); } else { OutputIntents outputIntents = attachment.outputIntents; byte[] iccProfileByteArray = File.ReadAllBytes(outputIntents.colorProfilePath); ICC_Profile icc = ICC_Profile.GetInstance(iccProfileByteArray); writer.SetOutputIntents(outputIntents.outputConditionIdentifier, outputIntents.outputCondition, outputIntents.registryName, outputIntents.info, icc); } //============= Create Exchange ECertificate ================= // 1 add ContentInformation.xml to document PdfArray attachmentArray = new PdfArray(); writer.ExtraCatalog.Put(new PdfName("AF"), attachmentArray); PdfFileSpecification contentSpec = this.EmbeddedAttachment(attachment.contentInformationXMLPath, attachment.attachmentName, attachment.attachmentMIME, new PdfName(attachment.attachmentType), writer, attachment.attachmentDescription); attachmentArray.Add(contentSpec.Reference); foreach (var item in attachment.fileAttachments) { contentSpec = this.EmbeddedAttachment(item.attachmentPath, item.attachmentName, item.attachmentMIME, new PdfName(item.attachmentType), writer, item.attachmentDescription); attachmentArray.Add(contentSpec.Reference); } // 2 add Electronic Document XMP Metadata ElectronicDocumentSchema ed = ElectronicDocumentSchema.generateED(attachment.attachmentName, attachment.documentVersion, attachment.documentID, attachment.documentOID); xmpWriter.AddRdfDescription(ed); string pdfaSchema = Properties.Resources.EDocument_PDFAExtensionSchema; // convert string to stream byte[] byteArray = Encoding.UTF8.GetBytes(pdfaSchema); //byte[] byteArray = Encoding.ASCII.GetBytes(contents); MemoryStream stream = new MemoryStream(byteArray); IXmpMeta edPDFAextension = XmpMetaFactory.Parse(stream); IXmpMeta originalXMP = xmpWriter.XmpMeta; XmpUtils.AppendProperties(edPDFAextension, originalXMP, true, true); }
private static void SetPdfAConformance(PdfReader reader, Document doc, MemoryStream ms) { // Create PdfAWriter with PdfAConformanceLevel.PDF_A_3B option if you // want to get a PDF/A-3b compliant document. PdfAWriter writer = PdfAWriter.GetInstance(doc, ms, _pdfaConformanceLevel); // Create XMP metadata. It's a PDF/A requirement. writer.CreateXmpMetadata(); doc.Open(); // Set output intent. PDF/A requirement. ICC_Profile icc = ICC_Profile .GetInstance(new FileStream(@"resources/sRGB Color Space Profile.icm", FileMode.Open)); writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc); // Creating PDF/A-3 compliant attachment. PdfDictionary parameters = new PdfDictionary(); parameters.Put(PdfName.MODDATE, new PdfDate()); PdfFileSpecification fileSpec = PdfFileSpecification.FileEmbedded( writer, _inputFilePath, "test.pdf", null, "application/pdf", parameters, 0); fileSpec.Put(new PdfName("AFRelationship"), new PdfName("Data")); writer.AddFileAttachment("test.pdf", fileSpec); PdfArray array = new PdfArray { fileSpec.Reference }; writer.ExtraCatalog.Put(new PdfName("AF"), array); doc.AddDocListener(writer); for (int i = 1; i <= reader.NumberOfPages; i++) { doc.SetPageSize(reader.GetPageSize(i)); doc.NewPage(); PdfContentByte cb = writer.DirectContent; PdfImportedPage page = writer.GetImportedPage(reader, i); int rotation = reader.GetPageRotation(i); if (rotation == 90 || rotation == 270) { cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else { cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0); } } }
private static PdfFileSpecification EmbeddedAttachment(string filePath, string fileName, string mimeType, PdfName afRelationship, PdfAWriter writer, string description) { PdfDictionary parameters = new PdfDictionary(); parameters.Put(PdfName.MODDATE, new PdfDate(File.GetLastWriteTime(filePath))); PdfFileSpecification fileSpec = PdfFileSpecification.FileEmbedded(writer, filePath, fileName, null, mimeType, parameters, 0); fileSpec.Put(new PdfName("AFRelationship"), afRelationship); writer.AddFileAttachment(description, fileSpec); return(fileSpec); }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7); writer.AddDeveloperExtension( PdfDeveloperExtension.ADOBE_1_7_EXTENSIONLEVEL3 ); // step 3 document.Open(); // step 4 // we prepare a RichMediaAnnotation RichMediaAnnotation richMedia = new RichMediaAnnotation( writer, new Rectangle(36, 400, 559, 806) ); // we embed the swf file PdfFileSpecification fs = PdfFileSpecification.FileEmbedded( writer, RESOURCE, "FestivalCalendar1.swf", null ); // we declare the swf file as an asset PdfIndirectReference asset = richMedia.AddAsset( "FestivalCalendar1.swf", fs ); // we create a configuration RichMediaConfiguration configuration = new RichMediaConfiguration( PdfName.FLASH ); RichMediaInstance instance = new RichMediaInstance(PdfName.FLASH); RichMediaParams flashVars = new RichMediaParams(); String vars = "&day=2011-10-13"; flashVars.FlashVars = vars; instance.Params = flashVars; instance.Asset = asset; configuration.AddInstance(instance); // we add the configuration to the annotation PdfIndirectReference configurationRef = richMedia.AddConfiguration( configuration ); // activation of the rich media RichMediaActivation activation = new RichMediaActivation(); activation.Configuration = configurationRef; richMedia.Activation = activation; // we add the annotation PdfAnnotation richMediaAnnotation = richMedia.CreateAnnotation(); richMediaAnnotation.Flags = PdfAnnotation.FLAGS_PRINT; writer.AddAnnotation(richMediaAnnotation); } }
/// <summary> /// Adds all of the file attachments. /// </summary> public void AddFileAttachments() { if (PageSetup.FileAttachments == null || !PageSetup.FileAttachments.Any()) { return; } foreach (var file in PageSetup.FileAttachments) { var fileInfo = new FileInfo(file.FilePath); var pdfDictionary = new PdfDictionary(); pdfDictionary.Put(PdfName.Moddate, new PdfDate(fileInfo.LastWriteTime)); var fs = PdfFileSpecification.FileEmbedded(PdfWriter, file.FilePath, fileInfo.Name, null, true, null, pdfDictionary); PdfWriter.AddFileAttachment(file.Description, fs); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 document.Add(new Paragraph( "This document contains a collection of PDFs," + " one per Stanley Kubrick movie." )); PdfCollection collection = new PdfCollection(PdfCollection.DETAILS); PdfCollectionSchema schema = _collectionSchema(); collection.Schema = schema; PdfCollectionSort sort = new PdfCollectionSort("YEAR"); sort.SetSortOrder(false); collection.Sort = sort; collection.InitialDocument = "Eyes Wide Shut"; writer.Collection = collection; PdfCollectionItem item; IEnumerable <Movie> movies = PojoFactory.GetMovies(1); foreach (Movie movie in movies) { PdfFileSpecification fs = PdfFileSpecification.FileEmbedded( writer, null, String.Format("kubrick_{0}.pdf", movie.Imdb), CreateMoviePage(movie) ); fs.AddDescription(movie.Title, false); item = new PdfCollectionItem(schema); item.AddItem("TITLE", movie.GetMovieTitle(false)); if (movie.GetMovieTitle(true) != null) { item.SetPrefix("TITLE", movie.GetMovieTitle(true)); } item.AddItem("DURATION", movie.Duration.ToString()); item.AddItem("YEAR", movie.Year.ToString()); fs.AddCollectionItem(item); writer.AddFileAttachment(fs); } } }
//static void Main(string[] args) //{ // PDFA3Invoice core = new PDFA3Invoice(); // String pdfFilePath = "in/test.pdf"; // String xmlFilePath = "in/ContentInformation.xml"; // String xmlFileName = "content.xml"; // String xmlVersion = "1.0"; // String documentID = "TIV0000012"; // String documentOID = ""; // String outputPath = "out/test.pdf"; // core.CreatePDFA3Invoice(pdfFilePath, xmlFilePath, xmlFileName, xmlVersion, // documentID, documentOID, outputPath); // Console.ReadLine(); //} public void CreatePDFA3Invoice(string pdfFilePath, string xmlFilePath, string xmlFileName, string xmlVersion, string documentID, string documentOID, string outputPath, string documentType) { // =========== Create PDF/A-3U Document ================= // Create PDF/A-3U writer instance from existing document PdfReader reader = new PdfReader(pdfFilePath); MemoryStream stream = new MemoryStream(); Document pdfAdocument = new Document(); PdfAWriter writer = this.CreatePDFAInstance(pdfAdocument, reader, stream); // Create Output Intents ICC_Profile icc = ICC_Profile.GetInstance("Resources/sRGB Color Space Profile.icm"); writer.SetOutputIntents("sRGB IEC61966-2.1", "", "http://www.color.org", "sRGB IEC61966-2.1", icc); PdfArray array = new PdfArray(); writer.ExtraCatalog.Put(new PdfName("AF"), array); //============= Create Exchange Invoice ================= // 1 add xml to document PdfFileSpecification contentSpec = this.EmbeddedAttachment(xmlFilePath, xmlFileName, "text/xml", new PdfName("Alternative"), writer, "Tax Invoice XML Data"); array.Add(contentSpec.Reference); //byte[] exchangeXMP = File.ReadAllBytes("Resources/EDocument_PDFAExtensionSchema.xml"); string stringExchangeXMP = File.ReadAllText("Resources/EDocument_PDFAExtensionSchema.xml"); byte[] exchangeXMP = Encoding.ASCII.GetBytes(stringExchangeXMP.Replace("@DocumentType", documentType)); writer.XmpMetadata = exchangeXMP; //// 2 add Electronic Document XMP Metadata //ElectronicDocument ed = ElectronicDocument.generateED(xmlFileName, xmlVersion, documentID, documentOID); //XmpWriter xmpWriter = writer.XmpWriter; //xmpWriter.AddRdfDescription(ed); //IXmpMeta edPDFAextension = XmpMetaFactory.Parse(new FileStream("Resources/EDocument_PDFAExtensionSchema.xml", FileMode.Open)); //IXmpMeta originalXMP = xmpWriter.XmpMeta; //XmpUtils.AppendProperties(edPDFAextension, originalXMP, true, true); pdfAdocument.Close(); reader.Close(); File.WriteAllBytes(outputPath, stream.ToArray()); }
virtual public void FileSpecCheckTest5() { Document document = new Document(); PdfAWriter writer = PdfAWriter.GetInstance(document, new FileStream(OUT + "fileSpecCheckTest5.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_3B); writer.CreateXmpMetadata(); document.Open(); Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12); document.Add(new Paragraph("Hello World", font)); FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read); ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream); iccProfileFileStream.Close(); writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc); MemoryStream txt = new MemoryStream(); StreamWriter outp = new StreamWriter(txt); outp.Write("<foo><foo2>Hello world</foo2></foo>"); outp.Close(); bool exceptionThrown = false; try { PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(writer, null, "foo.xml", txt.ToArray()); writer.AddFileAttachment(fs); } catch (PdfAConformanceException e) { if (e.GetObject() != null && e.Message.Equals("The file specification dictionary for an embedded file shall contain correct AFRelationship key.")) { exceptionThrown = true; } } if (!exceptionThrown) { Assert.Fail("PdfAConformanceException with correct message should be thrown."); } }
public void CreatePDFFile_old(string strPDFPath, string attachment, string password) { try { string fileName = Path.GetFileName(attachment); using (Document document = new Document(cPageSize.GetDocumentWithBackroundColor(cPageSize.A4, new BaseColor(245, 245, 245)), 0f, 0f, 0f, 17f)) { using (FileStream pdf = new FileStream(strPDFPath, FileMode.Create, FileAccess.Write, FileShare.None)) { using (PdfWriter pdfWriter = PdfWriter.GetInstance(document, pdf)) { document.Open(); var fs = PdfFileSpecification.FileEmbedded(pdfWriter, attachment, fileName, null); fs.AddDescription(fileName, false); PdfAnnotation annotation = new PdfAnnotation(pdfWriter, new Rectangle(1550f, 50f, 150f, 500f)); annotation.Put(PdfName.SUBTYPE, PdfName.FILEATTACHMENT); annotation.Put(PdfName.CONTENTS, new PdfString(fileName)); annotation.Put(PdfName.FS, fs.Reference); document.Add(new Paragraph("Attached files:")); Chunk linkChunk = new Chunk("this is what we need to achive using pdfanotation"); linkChunk.SetAnnotation(annotation); Phrase phrase = new Phrase(); phrase.Add(linkChunk); document.Add(phrase); document.Close(); pdfWriter.Close(); pdfWriter.Dispose(); } pdf.Close(); pdf.Dispose(); } document.Dispose(); } } catch (Exception ex) { } PasswordProtectPDF(strPDFPath, password); }
internal void ExtractAttachments(string file_name, string folderName, PdfWriter write) { PdfDictionary documentNames = null; PdfDictionary embeddedFiles = null; PdfDictionary fileArray = null; PdfDictionary file = null; PRStream stream = null; PdfReader reader = new PdfReader(file_name); PdfDictionary catalog = reader.Catalog; documentNames = (PdfDictionary)PdfReader.GetPdfObject(catalog.Get(PdfName.NAMES)); if (documentNames != null) { embeddedFiles = (PdfDictionary)PdfReader.GetPdfObject(documentNames.Get(PdfName.EMBEDDEDFILES)); if (embeddedFiles != null) { PdfArray filespecs = embeddedFiles.GetAsArray(PdfName.NAMES); for (int i = 0; i < filespecs.Size; i++) { i++; fileArray = filespecs.GetAsDict(i); file = fileArray.GetAsDict(PdfName.EF); foreach (PdfName key in file.Keys) { stream = (PRStream)PdfReader.GetPdfObject(file.GetAsIndirectObject(key)); string attachedFileName = folderName + fileArray.GetAsString(key).ToString(); byte[] attachedFileBytes = PdfReader.GetStreamBytes(stream); //graba el anexo extraido System.IO.File.WriteAllBytes(attachedFileName, attachedFileBytes); //adjunta los anexos PdfFileSpecification pfs = PdfFileSpecification.FileEmbedded(write, attachedFileName, fileArray.GetAsString(key).ToString(), null); write.AddFileAttachment(pfs); //borramos los archivos extraidos System.IO.File.Delete(attachedFileName); } } } } }
private void addAsAttachment(IDataExporter exporter, byte[] data) { if (string.IsNullOrEmpty(exporter.FileName)) { throw new InvalidOperationException("Please fill the exporter.FileName."); } if (string.IsNullOrEmpty(exporter.Description)) { exporter.Description = "Exported data"; } var pdfDictionary = new PdfDictionary(); pdfDictionary.Put(PdfName.Moddate, new PdfDate(DateTime.Now)); var fs = PdfFileSpecification.FileEmbedded(_sharedData.PdfWriter, null, exporter.FileName, data, true, null, pdfDictionary); _sharedData.PdfWriter.AddFileAttachment(exporter.Description, fs); }
public static PdfAnnotation ConvertAnnotation(PdfWriter writer, Annotation annot, Rectangle defaultRect) { switch (annot.AnnotationType) { case Annotation.URL_NET: return(new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((Uri)annot.Attributes[Annotation.URL]))); case Annotation.URL_AS_STRING: return(new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((String)annot.Attributes[Annotation.FILE]))); case Annotation.FILE_DEST: return(new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((String)annot.Attributes[Annotation.FILE], (String)annot.Attributes[Annotation.DESTINATION]))); case Annotation.SCREEN: bool[] sparams = (bool[])annot.Attributes[Annotation.PARAMETERS]; String fname = (String)annot.Attributes[Annotation.FILE]; String mimetype = (String)annot.Attributes[Annotation.MIMETYPE]; PdfFileSpecification fs; if (sparams[0]) { fs = PdfFileSpecification.FileEmbedded(writer, fname, fname, null); } else { fs = PdfFileSpecification.FileExtern(writer, fname); } PdfAnnotation ann = PdfAnnotation.CreateScreen(writer, new Rectangle(annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry()), fname, fs, mimetype, sparams[1]); return(ann); case Annotation.FILE_PAGE: return(new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((String)annot.Attributes[Annotation.FILE], (int)annot.Attributes[Annotation.PAGE]))); case Annotation.NAMED_DEST: return(new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((int)annot.Attributes[Annotation.NAMED]))); case Annotation.LAUNCH: return(new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((String)annot.Attributes[Annotation.APPLICATION], (String)annot.Attributes[Annotation.PARAMETERS], (String)annot.Attributes[Annotation.OPERATION], (String)annot.Attributes[Annotation.DEFAULTDIR]))); default: return(new PdfAnnotation(writer, defaultRect.Left, defaultRect.Bottom, defaultRect.Right, defaultRect.Top, new PdfString(annot.Title, PdfObject.TEXT_UNICODE), new PdfString(annot.Content, PdfObject.TEXT_UNICODE))); } }
public void CreatePdf(String dest) { Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(dest, FileMode.Create)); document.Open(); document.Add(new Paragraph("Portable collection")); PdfCollection collection = new PdfCollection(PdfCollection.TILE); writer.Collection = collection; PdfFileSpecification fileSpec = PdfFileSpecification.FileEmbedded(writer, DATA, "united_states.csv", null); writer.AddFileAttachment("united_states.csv", fileSpec); fileSpec = PdfFileSpecification.FileEmbedded(writer, HELLO, "hello.pdf", null); writer.AddFileAttachment("hello.pdf", fileSpec); fileSpec = PdfFileSpecification.FileEmbedded(writer, IMG, "berlin2013.jpg", null); writer.AddFileAttachment("berlin2013.jpg", fileSpec); document.Close(); }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 PdfFileSpecification fs = PdfFileSpecification.FileEmbedded( writer, RESOURCE, "foxdog.mpg", null ); writer.AddAnnotation(PdfAnnotation.CreateScreen( writer, new Rectangle(200f, 700f, 400f, 800f), "Fox and Dog", fs, "video/mpeg", true )); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 Image img = Image.GetInstance(IMG_BOX); document.Add(img); List list = new List(List.UNORDERED, 20); PdfDestination dest = new PdfDestination(PdfDestination.FIT); dest.AddFirst(new PdfNumber(1)); IEnumerable <Movie> box = PojoFactory.GetMovies(1) .Concat(PojoFactory.GetMovies(4)) ; foreach (Movie movie in box) { if (movie.Year > 1960) { PdfFileSpecification fs = PdfFileSpecification.FileEmbedded( writer, null, String.Format("kubrick_{0}.pdf", movie.Imdb), CreateMoviePage(movie) ); fs.AddDescription(movie.Title, false); writer.AddFileAttachment(fs); ListItem item = new ListItem(movie.MovieTitle); PdfTargetDictionary target = new PdfTargetDictionary(true); target.EmbeddedFileName = movie.Title; PdfAction action = PdfAction.GotoEmbedded(null, target, dest, true); Chunk chunk = new Chunk(" (see info)"); chunk.SetAction(action); item.Add(chunk); list.Add(item); } } document.Add(list); } }
// --------------------------------------------------------------------------- /** * Creates the PDF. * @return the bytes of a PDF file. */ public byte[] CreatePdf() { IEnumerable <Movie> movies = PojoFactory.GetMovies(1); using (MemoryStream ms = new MemoryStream()) { using (Document document = new Document()) { PdfWriter writer = PdfWriter.GetInstance(document, ms); document.Open(); document.Add(new Paragraph( "'Stanley Kubrick: A Life in Pictures'" + " is a documentary about Stanley Kubrick and his films:" )); StringBuilder sb = new StringBuilder(); sb.AppendLine("<movies>"); List list = new List(List.UNORDERED, 20); foreach (Movie movie in movies) { sb.AppendLine("<movie>"); sb.AppendLine(String.Format( "<title>{0}</title>", XMLUtil.EscapeXML(movie.MovieTitle, true) )); sb.AppendLine(String.Format("<year>{0}</year>", movie.Year)); sb.AppendLine(String.Format( "<duration>{0}</duration>", movie.Duration )); sb.AppendLine("</movie>"); ListItem item = new ListItem(movie.MovieTitle); list.Add(item); } document.Add(list); sb.Append("</movies>"); PdfFileSpecification fs = PdfFileSpecification.FileEmbedded( writer, null, "kubrick.xml", Encoding.UTF8.GetBytes(sb.ToString()) //txt.toByteArray() ); writer.AddFileAttachment(fs); } return(ms.ToArray()); } }
public static void Main() { // NOTE: // When used in trial mode, the library imposes some restrictions. // Please visit http://bitmiracle.com/pdf-library/trial-restrictions.aspx // for more information. using (PdfDocument pdf = new PdfDocument(@"Sample Data\Attachments.pdf")) { PdfFileSpecification spec = pdf.SharedAttachments["File Attachment testing.doc"]; if (spec != null && spec.Contents != null) { const string pathToFile = "attachment.doc"; spec.Contents.Save(pathToFile); Process.Start(pathToFile); } else { MessageBox.Show("Can't save shared attachment", "Error"); } } }
public void Write(Stream stream, string[] pfade) { using (Document document = new Document()) { PdfWriter writer = PdfWriter.GetInstance(document, stream); document.Open(); document.Add(new Paragraph(" ")); PdfIndirectReference parentFolderObjectReference = writer.PdfIndirectReference; PdfCollection collection = new PdfCollection(PdfCollection.DETAILS); PdfCollectionSchema schema = CollectionSchema(); collection.Schema = schema; collection.Sort = new PdfCollectionSort(keys); collection.Put(new PdfName("Vorlagen BA"), parentFolderObjectReference); writer.Collection = collection; PdfFileSpecification fs; PdfCollectionItem item; int nummer = 1; foreach (string pfad in pfade) { String Filename = Path.GetFileName(pfad); fs = PdfFileSpecification.FileEmbedded(writer, pfad, string.Format("{0} - {1}", nummer, Filename), null); item = new PdfCollectionItem(schema); item.AddItem("Type", "pdf"); fs.AddCollectionItem(item); fs.AddDescription(GetDescription(Filename), false); writer.AddFileAttachment(fs); nummer++; } document.Close(); } }