How to convert a byte array to pdf

Arbenita Musliu

I am building an app that modifies a word 2010 document and it should be downloaded as pdf.I write a code to convert word to pdf but it is converting the document I upload not the modified word. How can I convert modified word to PDF.Below is the function which is not converting modified word. protected void btnUpload_Click(object sender, EventArgs e) {

        if (FileUploadControl.HasFile)

            {
                string fileNameFromUser = FileUploadControl.FileName;
                var fiFileName = new System.IO.FileInfo(fileNameFromUser);

                using (MemoryStream ms = new MemoryStream())
                {
                    ms.Write(FileUploadControl.FileBytes, 0, FileUploadControl.FileBytes.Length);

                    using (WordprocessingDocument sDoc = WordprocessingDocument.Open(ms, true))
                    {

                    }
                    lblMessage.Text = "Dokumenti u ngarkua me sukses!";
                    Session["ByteArray"] = FileUploadControl.FileBytes;
                    Session["fileNameFromUser"] = fileNameFromUser;
                }



        }
        byte[] byteArray = (byte[])(Session["ByteArray"]);
        if (byteArray != null)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    ms.Write(byteArray, 0, byteArray.Length);
                    using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true))
                    {
                        var body = wDoc.MainDocumentPart.Document.Body;
                        var lastParagraf = body.Elements<Paragraph>().LastOrDefault();
                        var newParagraf = new Paragraph(

                            new Run(
                                new Text("Perdoruesi:" + " " + User.Identity.Name)));

                        var newParagraf2 = new Paragraph(

                           new Run(
                               new Text("Data dhe ora:" + " " + DateTime.Now.ToString())));

                        var newParagraf3 = new Paragraph(

                           new Run(
                               new Text("Kodi unik:" + " " + randomstring(14))));

                        var newParagraf4 = new Paragraph(

                          new Run(
                              new Text("Shifra:" )));

                        lastParagraf.InsertAfterSelf(newParagraf);
                        lastParagraf.InsertAfterSelf(newParagraf2);
                        lastParagraf.InsertAfterSelf(newParagraf3);
                        lastParagraf.InsertAfterSelf(newParagraf4);
                    }
                    Session["ByteArray"] = ms.ToArray();
                    lblMessage.Text = "U ngarkua dhe u vulos dokumenti!";

                    Guid pdfFileGuid = Guid.NewGuid();

                    var filePath = Path.GetTempFileName();
                    FileUploadControl.SaveAs(filePath);
                    var appWord = new Microsoft.Office.Interop.Word.Application();
                    var wordDoc = appWord.Documents.Open(filePath);
                    var convertedFilePath = Path.GetTempFileName();
                    wordDoc.ExportAsFixedFormat(convertedFilePath, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
                    Response.Clear();
                    Response.AddHeader("content-disposition", "attachment; filename=Converted.Pdf");
                    Response.AddHeader("content-type", "application/pdf");
                    Response.TransmitFile(convertedFilePath);
                    File.Delete(filePath);
                    File.Delete(convertedFilePath);
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = "ERROR:" + ex.Message.ToString();
            }
        }
        else
        {
            lblMessage.Text = "Nuk e keni zgjedhur dokumentin apo formati i dokumentit nuk pershtatet!";
        }
    }
Marc Gravell

Currently, here you load the data from the FileUploadControl into session:

Session["ByteArray"] = FileUploadControl.FileBytes;

You then load the data from session into a MemoryStream that you use to open the document for editing:

    byte[] byteArray = (byte[])(Session["ByteArray"]);
    if (byteArray != null)
    {
        try
        {
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(byteArray, 0, byteArray.Length);
                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true))

At the end of this, after your edits, you copy the updated content back to session:

            lastParagraf.InsertAfterSelf(newParagraf3);
            lastParagraf.InsertAfterSelf(newParagraf4);
        }
        Session["ByteArray"] = ms.ToArray();

but; that's the last time we see session used; you then write the uploaded file to a temporary file, and use that to perform Word automation:

var filePath = Path.GetTempFileName();
FileUploadControl.SaveAs(filePath);
var appWord = new Microsoft.Office.Interop.Word.Application();
var wordDoc = appWord.Documents.Open(filePath);

So yes: this will convert the original file as uploaded, because FileUploadControl is unrelated to the changes you made. Instead, perhaps try:

var filePath = Path.GetTempFileName();
File.WriteAllBytes(filePath, (byte[])Session["ByteArray"]);
var appWord = new Microsoft.Office.Interop.Word.Application();
var wordDoc = appWord.Documents.Open(filePath);

This should then include the changes.


Additional side observations:

  • Word automation is unsupported and not recommended on web-servers; if it works for you: great, but just be aware that if it suddenly breaks you'll be on your own
  • be careful that you're not leaving files scattered on disk, or lots of open Word instances / files; basically: check you're not "leaking" (appWord, wordDoc, filePath, convertedFilePath etc - all probably need some finally love)
  • putting Word files into session-state (Session) probably isn't a good or necessary idea; I would recommend just using a local byte[] or similar throughout in this method, and remove Session["ByteArray"] completely

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related