logo
Welcome Guest! To enable all features please Login or Register.

Notification

Icon
Error

Options
Go to last post Go to first unread
Paul Rayman  
#1 Posted : Wednesday, July 1, 2020 8:17:27 AM(UTC)
Paul Rayman

Rank: Administration

Groups: Administrators
Joined: 1/5/2016(UTC)
Posts: 902

Thanks: 3 times
Was thanked: 110 time(s) in 107 post(s)
Code:

using(var doc = PdfDocument.CreateNew())
{
    var page = doc.Pages.InsertPageAt(0, 612, 792);

    var data = File.ReadAllBytes(@"file attachment.pdff");

    AddAttachmentAsAnnotation(page, data, "TestAttachemnt1.pdf");
    AddAttachmentIntoCatalog(doc, data, "TestAttachemnt2.pdf");
    doc.Save(@"test.pdf", SaveFlags.NoIncremental);
}

private static void AddAttachmentAsAnnotation(PdfPage page, byte[] data, string name)
{
    var annot = new PdfFileAttachmentAnnotation(page, FileIconNames.Paperclip, name, data, 50, 50);
    if (page.Annots == null)
        page.CreateAnnotations();
    page.Annots.Add(annot);
}

private static void AddAttachmentIntoCatalog(PdfDocument doc, byte[] data, string name)
{
    if (!doc.Root.ContainsKey("Names"))
        doc.Root["Names"] = PdfTypeDictionary.Create();
    var names = doc.Root["Names"].As<PdfTypeDictionary>();

    if (!names.ContainsKey("EmbeddedFiles"))
        names["EmbeddedFiles"] = PdfTypeDictionary.Create();
    var embeddedFiles = names["EmbeddedFiles"].As<PdfTypeDictionary>();

    if (!embeddedFiles.ContainsKey("Names"))
        embeddedFiles["Names"] = PdfTypeArray.Create();
    var attachments = embeddedFiles["Names"].As<PdfTypeArray>();

    attachments.Add(PdfTypeString.Create(name, true));
    var attachmentDict = PdfTypeDictionary.Create();
    attachments.Add(attachmentDict);
    var fs = new PdfFileSpecification(doc, attachmentDict); 
    fs.EmbeddedFile = new PdfFile(data);
    fs.FileName = name;
}
Users browsing this topic
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.