How to programmatically print files and web pages to PDF through "Microsoft print to PDF"?

4k Views Asked by At

I'm working on a UWP application, written in c#, and I need to convert to pdf: - office documents (doc, docx, xls, xlsx, ppt, pptx) - images - Web pages

The application has to work in x86, x64, ARM, ARM64 architectures.

I know there are third party converter libraries on the market but only a few of them work in an ARM64 context or in UWP.

My idea is to use (in Windows 10) the "Microsoft PDF printer" that allows the users to save most of the file formats to PDF.

I found many posts asking for the same question but none of them really contains a helpful answer.

The code I found and tested is the following:

PrintDocument doc = new PrintDocument()
{
//DocumentName = safeDir + fileName,
    PrinterSettings = new PrinterSettings()
    {
        // set the printer to 'Microsoft Print to PDF'
        PrinterName = "Microsoft Print to PDF",

        // tell the object this document will print to file
        PrintToFile = true,


        // set the filename to whatever you like (full path)
        PrintFileName = safeDir + fileName,
    }
};
doc.Print();

The above code generates a valid but empty pdf. How should I set the original file content?

For example, if I have a Word file named myreport.docx, should I convert it to byte array and set it in somewhere?

Thank you in advance.

2

There are 2 best solutions below

2
On

When using the PrintDocument class, you should read the file you are trying to print into a filestream as in the example here: https://learn.microsoft.com/en-us/dotnet/api/system.drawing.printing.printdocument?view=netframework-4.8

I personally prefer to use the Microsoft.Office.Interop libraries for Word and Excel to print. With these you just have to load the document, set the printer to "Adobe PDF", and save the document.

2
On

In UWP we use PrintDocument to print UIElement. And this is official tutorial. And this is code sample.

How to Print Web Pages

We need get WebViewBrush first before print. Please refer this case reply to get web content. Then view above code sample to print the WebViewBrush to pdf. And I have replied the similar case that you could refer.

How to print file

UWP PrintDocument just support print UIElement, so we need display the file content with uwp control then print. For detail steps please refer official code sample scenario 4.