且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UWP生成PDF-***方法

更新时间:2023-02-12 21:28:29

当前,有许多第三方付费软件包可用于在UWP中生成PDF,例如 XFinium .对于免费的库,例如 PDFSharp 在UWP中不可用.由于您不想要付费应用程序,因此您可以考虑使用免费库创建经典应用程序,然后创建一个AppService来处理它.有关更多详细信息,请参考 AppServiceBridgeSample .

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.

拥有XAML页面并通过打印将其转换为PDF

Have a XAML page and convert it PDF by printing

通过打印功能可以生成PDF做得好.但是由于您的要求通过隐藏的打印对话框"是不可能的,因此无法隐藏打印UI进行打印.

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.

使用WebView和HTML做类似的事情

Do something similar with an WebView and HTML

打开的 jsPDF 库可以帮助您通过JavaScript生成HTML到PDF.并且您可以通过

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

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);

毕竟,您可以考虑自己编写PDF文件格式.

After all, you can consider Write the PDF file format yourself. Here is a document for windows phone but you may still reference.