如何生成 Angular 应用的服务器端 PDF?

7
我们有一个使用Angular(v4)的应用程序,可以通过我们的API接收JSON数据,并从文件存储中获取图像生成表单。每个使用该应用程序的客户端都拥有数百个包含不同数据和图像的表单。现在有一个需求,要求允许客户将其表单导出为PDF文件并打包成zip文件。
我们正在探索的解决方案策略是,当收到客户的导出请求时,服务器将在无头浏览器中加载客户可以访问的每个表单,Angular将构建表单,然后服务器将要求浏览器生成PDF截图。然后将这些PDF文件进行压缩,并通过电子邮件或下载链接发送给客户。
我们遇到的问题是,从服务器端生成Angular应用程序的屏幕截图失败了。
作为更简单的测试网站,我们还尝试使任何这些工具与当前的Angular文档网站https://angular.io/guide/quickstart一起工作。但目前所有尝试均失败。
  • wkhtmltopdf - Gets to our loading user info spinner, but no content arrives, even after waiting for 90 seconds. We get errors in the JS output.

    This is the command we've been using to snap the Angular docs site which just generates a white PDF:

    ~/render/wkhtmltox/bin$ ./wkhtmltopdf --debug-javascript --no-stop-slow-scripts --javascript-delay 90000 https://angular.io/guide/quickstart angular_quickstart.pdf 
    Loading pages (1/6)
    Warning: undefined:0 TypeError: setting a property that has only a getter
    Counting pages (2/6)                                               
    Resolving links (4/6)                                                       
    Loading headers and footers (5/6)                                           
    Printing pages (6/6)
    Done             
    
  • PhantomJS - Appears to do a bit better than wkhtmltopdf because it can get to our "loading content" spinner which means that the app knows a user it logged in. However, even when waiting and polling for DOM changes, we get no changes after the initial load.

    When working with the Angular docs site, this also fails with a white screen:

    ~/render/phantomjs-2.1.1-linux-x86_64$ bin/phantomjs examples/rasterize.js https://angular.io/guide/quickstart angular_quickstart.pdf 
    ReferenceError: Can't find variable: WeakMap
    
      https://angular.io/main.f0610805f4aad19da4be.bundle.js:1 in cDNt
      https://angular.io/inline.2826385ad3e299c6d1c1.bundle.js:1 in n
      https://angular.io/main.f0610805f4aad19da4be.bundle.js:1
      https://angular.io/inline.2826385ad3e299c6d1c1.bundle.js:1 in n
      https://angular.io/inline.2826385ad3e299c6d1c1.bundle.js:1 in webpackJsonp
    
  • Puppeteer - We haven't dug into headless Chrome fully, but initial tests with https://try-puppeteer.appspot.com/ and the Angular docs site have failed with:

    Error running your code. Error: Navigation Timeout Exceeded: 30000ms exceeded
    

有没有人能指导我一个能够截取Angular文档并生成PDF的可行解决方案?希望我们能够根据这个方案来适应我们的应用程序。请确保您的解决方案可以截取在Angular 5上运行的Angular文档。

当涉及到服务器端技术时,我们主要使用Python,但如果有一个可靠的解决方案,我们可以安装node并运行docker容器。

1个回答

2

最简单的方法可能是使用Chrome:

 chrome.exe --headless --enable-logging --disable-gpu --print-to-pdf="D:\temp\file.pdf" https://angular.io/guide/quickstart

请参考创建PDF章节,其中涉及到IT技术。

你能够使用 https://angular.io/guide/quickstart 来使它工作吗?它一直在我这卡住了。 - jamesc
看起来你必须指定 PDF 的路径,请查看更新后的答案。 - kemsky
有一个控制无头Chromium的库:https://developers.google.com/web/tools/puppeteer/ - Der_Meister

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接