I'm working on a UWP app and as one of the requirements I need to generate a PDF file dynamically.
There are a few contraints / requirements that I need to concider:
I have had couple of ideas on how to approach this:
Has anyone achieved something similar in the past and if so - what approach have you taken?
Currently, there are many third party paid packages for generating PDF in UWP, such as Syncfusion and XFinium. For free libraries like PDFSharp that are not available in UWP. Since you don't want a paid one, you may consider to create classical application with free libraries and then create an AppService to handle it. For more details please reference AppServiceBridgeSample.
Have a XAML page and convert it PDF by printing
Generate the PDF by printing feature can work well. But for your requirements "through a hidden print dialog" is not possible, print UI cannot be hidden to print.
Do something similar with an WebView and HTML
The open jsPDF library can help you generate HTML to PDF by JavaScript. And you can get the PDF result return by InvokeScriptAsync from WebView. For example:
JavaScript
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"></script>
<script type='text/javascript'>
function print() {
var doc = new jsPDF()
doc.text('Hello world!', 10, 10);
doc.circle(50, 50, 50);
var pdfresult = doc.output();
document.getElementById('myDiv').innerText = pdfresult;
//doc.save('a4.pdf');
return pdfresult;
}
</script>
</head>
<body>
<div id='myDiv'>Hello</div>
</body>
</html>
WebView
Webview.Navigate(new Uri("ms-appx-web:///Assets/test.html"));
string pdfresult = await Webview.InvokeScriptAsync("eval", new string[] { "print()" });
StorageFile pdf = await ApplicationData.Current.LocalFolder.CreateFileAsync("test.pdf");
await FileIO.WriteTextAsync(pdf, pdfresult);
After all, you can consider Write the PDF file format yourself. Here is a document for windows phone but you may still reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With