2

I have a sequence of bytes as follows (Word format) exported from crystal report

 Stream stream = cryRpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.WordForWindows);

I would like to convert that stream to a PDF stream to be stored in a varbinary column in sql server database.

There is a barcode in the document and i am unable to embed it when I export to pdf. Exporting to word works though so I want to try from Word to PDF Can anyone assist me in getting this PDF byte[]?

CoDeGiRl
  • 174
  • 2
  • 16
  • Are you looking for: [How do I convert Word files to PDF programmatically?](http://stackoverflow.com/questions/607669/how-do-i-convert-word-files-to-pdf-programmatically/608153) – Corak Jan 14 '15 at 15:50
  • Hi Corak, No I want to do this programatically, convert a word byte [] to a pdf byte[] – CoDeGiRl Jan 14 '15 at 15:52
  • 2
    You have to convert the Word-Document to a PDF-Document (using some high level library), then you may read the Bytes of this PDF-Document/File. – DrKoch Jan 14 '15 at 15:54
  • 2
    @CoDeGiRl, you could accomplish that by writing the byte[] to a file and using the answer to the question Corak linked to. It's nontrivial (to put it lightly) to convert a Word document to a PDF document without involving Word itself. – adv12 Jan 14 '15 at 15:54
  • DrKotch, when you say "You have to convert the Word-Document to a PDF-Document" do you mean a physical pdf file on disk? – CoDeGiRl Jan 14 '15 at 16:14

1 Answers1

0

You can do that using the Microsoft.Office.Interop.Word NuGet Package. Once you added it on your application you can flush your Byte Array to a temporary file, then open the temp file with Interop.Word, work with it, save the result and read the result back into a Byte Array.

Here's a sample code snippet that does just that:

// byte[] fileBytes = getFileBytesFromDB();
var tmpFile = Path.GetTempFileName();
File.WriteAllBytes(tmpFile, fileBytes);

Application app = new word.Application();
Document doc = app.Documents.Open(filePath);

// Save DOCX into a PDF
var pdfPath = "path-to-pdf-file.pdf";
doc.SaveAs2(pdfPath, word.WdSaveFormat.wdFormatPDF);

doc.Close();
app.Quit(); // VERY IMPORTANT: do this to close the MS Word instance
byte[] pdfFileBytes = File.ReadAllBytes(pdfPath);
File.Delete(tmpFile);

For more info regarding the topic you can also read this post on my blog.

Darkseal
  • 9,205
  • 8
  • 78
  • 111