最佳方法将HTML页面转换为PDF文件。

huangapple go评论70阅读模式
英文:

Best way to convert HTML page into PDF file

问题

我正在编写一个名为Convert-HTML-TO-PDF的新服务。但是现在我很困惑应该选择哪种方式。

我可以采用的实现方式:

  • 使用"无头"浏览器捕获HTML页面并转换为PDF。
  • 使用Java/Node库进行转换。该库会在PDF文件中创建与HTML相关的组件,然后进行渲染。

现在,请帮我理解哪种是实现这个服务最佳的方式,以及为什么会这样!

【更新】

每种方法的优缺点是什么?

英文:

I am writing a new service Convert-HTML-TO-PDF. But now I am confused that what way should I prefer.

What ways I have to implement:

  • Use Head-less browser and capture the HTML page and convert to PDF
  • Use Java/Node Lib to convert. Which will create HTML relevant component in PDF file and then render?

Now, please help me to understand what will be the best way to implement a service and why!

[update]

And what will be the advantages and disadvantages of each approach

答案1

得分: 1

以下是翻译好的内容:

在我看来,最佳前进方式始终取决于您已经具备的经验以及您采取的方法。这里没有对与错,每个人都必须根据自己的偏好来做出决定。

每种方法都有优势和劣势。其中一些是:

无头浏览器:<br/>
优势:

  • 不需要大型库,因此非常节省内存

劣势:

  • 必须在计算机/服务器上安装所需的浏览器
  • 不同浏览器的渲染可能不同

库:<br/>
优势:

  • 提供不同的库
  • 对于流行的库,有很好的文档和代码示例

劣势:

  • 升级到较新版本时,通常需要调整代码。
  • 升级到较新版本时,结果可能会有所不同。

在我的项目中,我使用了一个无头 Chrome 浏览器。为此,我在 Github 上找到了一个易于使用的 API,它使用了 Chrome 的 DevTools。

它还包括了一个 简单的示例,说明如何将页面打印成 PDF。

为了满足我的需求,我定制了这个示例,并将 HTML 写入临时文件,然后导航到该文件。

// 导航到 HTML 文件
page.navigate(htmlTempFile.getAbsolutePath());

我不能确定这是否是最佳方法,但对我来说,这是最简单和最易理解的方法。

英文:

In my view, the best way forward always depends on what you already have experience with and what approach you take. There is no right or wrong here, everyone has to decide that for themselves based on their preferences.

Each approach has advantages and disadvantages. Some of them are:

Headless Browser:<br/>
Advantage:

  • No large Libs necessary, therefore very memory saving

Disadvantage

  • the desired browser must be installed on the computer/server
  • rendering may differ for different browsers

Library:<br/>
Advantage:

  • different libraries available
  • for the popular libs there is a good documentation and code examples

Disadvantage

  • When upgrading to a newer version, code usually needs to be adapted.
  • When upgrading to a newer version, the result may look different.

In my projects I use a headless chrome browser. For this I found an easy to use api on Github, which uses the DevTools of Chrome.

It also includes a simple example how to print a page into a PDF.

For my purposes I have customized this example and write the HTML into a temporary file and then navigate to that file.

// Navigate to HTML-File
page.navigate(htmlTempFile.getAbsolutePath());

I can't say if this is the best way, but for me this was the easiest and most understandable way

huangapple
  • 本文由 发表于 2020年7月27日 14:59:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63110206.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定