none
Embed PDF file into docx - Convert PDF file bytes to .bin using C#

    Question

  • Hi,

    I need to embed PDF file into word file using open xml library. I have gone through various blogs but there is no concrete answer to implement this using only c# code. Can you please how can I covert .PDF to .bin and how can I use this .bin to embed in word document?

    Below is sample code. Here I am directly feeding PDF file bytes to embedded object part. I tried by converting PDF file to bin file using online converter and feed that bin data to embedded object part, but it did not work.

    public static void EmbedDocument(byte[] mainFileBytes, byte[] pdfFilebytes, string insertLocationTag, string outputFilePath)
            {
                Console.WriteLine("Embedding...");
                var fileStream = new MemoryStream();
                fileStream.Write(mainFileBytes, 0, mainFileBytes.Length);
    
                using (WordprocessingDocument myDoc = WordprocessingDocument.Create(@"D:\Helper Projects\TestOpenXML\Documents\Temp_" + DateTime.Now.Ticks + ".docx", WordprocessingDocumentType.Document))
                {
    
                    MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
    
                    mainPart.Document = new Document();
    
                    mainPart.Document.Body = new Body();
    
                    ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Png);
    
                    imagePart.FeedData(File.Open(@"D:\Helper Projects\TestOpenXML\Documents\Main\PDFICon.png", FileMode.Open));
    
                    EmbeddedPackagePart embeddedObjectPart =
    
                    //mainPart.AddEmbeddedPackagePart(@"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                    mainPart.AddEmbeddedPackagePart(@"application/vnd.openxmlformats-officedocument.oleObject");
    
                    //embeddedObjectPart.FeedData(File.Open(@"D:\Helper Projects\TestOpenXML\Documents\Main\Book1.xlsx", FileMode.Open));
                    embeddedObjectPart.FeedData(File.Open(@"D:\Helper Projects\TestOpenXML\Documents\Main\Empty Template.pdf", FileMode.Open));
    
                    Paragraph p = CreateEmbeddedObjectParagraph(mainPart.GetIdOfPart(imagePart), mainPart.GetIdOfPart(embeddedObjectPart));
    
                    OpenXmlElement parent = mainPart.Document.Body;
    
                    parent.AppendChild(p);
    
                    mainPart.Document.Save();
                }
    
                Console.WriteLine("Done!");
            }
    
            static Paragraph CreateEmbeddedObjectParagraph(string imageId, string embedId)
    
            {
                Paragraph p =
    
                new Paragraph(
    
                new Run(
    
                new EmbeddedObject(
    
                new V.Shapetype(
    
                new V.Stroke() { JoinStyle = V.StrokeJoinStyleValues.Miter },
    
                new V.Formulas(
    
                new V.Formula() { Equation = "if lineDrawn pixelLineWidth 0" },
    
                new V.Formula() { Equation = "sum @0 1 0" },
    
                new V.Formula() { Equation = "sum 0 0 @1" },
    
                new V.Formula() { Equation = "prod @2 1 2" },
    
                new V.Formula() { Equation = "prod @3 21600 pixelWidth" },
    
                new V.Formula() { Equation = "prod @3 21600 pixelHeight" },
    
                new V.Formula() { Equation = "sum @0 0 1" },
    
                new V.Formula() { Equation = "prod @6 1 2" },
    
                new V.Formula() { Equation = "prod @7 21600 pixelWidth" },
    
                new V.Formula() { Equation = "sum @8 21600 0" },
    
                new V.Formula() { Equation = "prod @7 21600 pixelHeight" },
    
                new V.Formula() { Equation = "sum @10 21600 0" }),
    
                new V.Path() { AllowGradientShape = TrueFalseValue.FromBoolean(true), ConnectionPointType = OVML.ConnectValues.Rectangle, AllowExtrusion = TrueFalseValue.FromBoolean(true) },
    
                new OVML.Lock() { Extension = V.ExtensionHandlingBehaviorValues.Edit, AspectRatio = TrueFalseValue.FromBoolean(true) }
    
                )
                { Id = "_x0000_t75", CoordinateSize = "21600,21600", Filled = TrueFalseValue.FromBoolean(false), Stroked = TrueFalseValue.FromBoolean(false), OptionalNumber = 75, PreferRelative = TrueFalseValue.FromBoolean(true), EdgePath = "m@4@5l@4@11@9@11@9@5xe" },
    
                new V.Shape(
    
                new V.ImageData() { Title = "", RelationshipId = imageId }
    
                )
                { Id = "_x0000_i1025", Style = "width:64pt;height:64pt", Ole = new TrueFalseBlankValue(), Type = "#_x0000_t75" },
    
                //new OVML.OleObject() { Type = OVML.OleValues.Embed, ProgId = "Excel.Sheet.12", ShapeId = "_x0000_i1025", DrawAspect = OVML.OleDrawAspectValues.Content, ObjectId = "_1307530183", Id = embedId }
                new OVML.OleObject() { Type = OVML.OleValues.Embed, ProgId = "AcroExch.Document.11", ShapeId = "_x0000_i1025", DrawAspect = OVML.OleDrawAspectValues.Content, ObjectId = "_1307530183", Id = embedId }
                )
                {
                    DxaOriginal = "1543",
                    DyaOriginal = "991",
                })
                );
    
                return p;
            }

     Thanks in advance.
    lundi 16 avril 2018 12:55

Toutes les réponses

  • Hello Bhargav_Gaglani,

    Have you checked if these two links could work for you?

    How can I embed any file type into Microsoft Word without interop assemblies
    Embedding Any File Type, Like PDF, in an Open XML File

    Best Regards,

    Terry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    mardi 17 avril 2018 10:12
    Modérateur
  • Hi Terry,

    I tried mentioned approach, but below code is failing for me. I tried by adding mentioned HKey but no luck.

    // note 1: if you get 'Use of Ole1 services requiring DDE windows is disabled' error, make sure the executing thread is STA
          //
          // note 2: if you want packager to succeed on PDF files instead of reporting 0x8000ffff (E_UNEXPECTED), make sure
          // there exists a key named "PackageOnFileDrop", like this: HKEY_CLASSES_ROOT\AcroExch.Document.DC\PackageOnFileDrop
          //
          IDataObject ps; // from System.Runtime.InteropServices.ComTypes
          CheckHr(OleCreateFromFile(
              Guid.Empty,
              inputFile,
              typeof(IDataObject).GUID,
              0,
              IntPtr.Zero,
              IntPtr.Zero,
              storage,
              out ps));

    jeudi 19 avril 2018 09:25