Skip to content

Instantly share code, notes, and snippets.

@OlafD
Created March 6, 2019 10:48
Show Gist options
  • Save OlafD/be11d10d2975e114dfa3c387c71e8789 to your computer and use it in GitHub Desktop.
Save OlafD/be11d10d2975e114dfa3c387c71e8789 to your computer and use it in GitHub Desktop.
Simple sample code to convert a docx-file to pdf using Aspose.Words. The relevant part is the method SaveAsPdf(). The Nuget package for Aspose.Words needs to be added to the project.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Aspose.Words;
using Aspose.Pdf;
namespace PDFToolsTester
{
class Program
{
static void Main(string[] args)
{
string docxFilename = "C:\\Temp\\MyDocument.docx";
string pdfFilename = "C:\\Temp\\MyDocument.pdf";
using (FileStream fs = new FileStream(docxFilename, FileMode.Open))
{
MemoryStream msPdf = SaveAsPdf(fs);
if (msPdf != null)
{
using (FileStream fsPdf = new FileStream(pdfFilename, FileMode.Create))
{
msPdf.CopyTo(fsPdf, (int)msPdf.Length);
fsPdf.Flush();
fsPdf.Close();
}
msPdf.Dispose();
}
}
}
static MemoryStream SaveAsPdf(Stream fs)
{
MemoryStream result = null;
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
using (MemoryStream ms = new MemoryStream(buffer, false))
{
Aspose.Words.Document document = new Aspose.Words.Document(ms);
using (MemoryStream msPdf = new MemoryStream())
{
document.Save(msPdf, Aspose.Words.SaveFormat.Pdf);
msPdf.Position = 0;
result = new MemoryStream((int)msPdf.Length);
msPdf.CopyTo(result);
result.Position = 0;
}
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment