Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

javascript - 使用JavaScript在div中从HTML生成pdf(Generate pdf from HTML in div using Javascript)

I have the following html code:

(我有以下html代码:)

<!DOCTYPE html>
<html>
    <body>
        <p>don't print this to pdf</p>
        <div id="pdf">
            <p><font size="3" color="red">print this to pdf</font></p>
        </div>
    </body>
</html>

All I want to do is to print to pdf whatever is found in the div with an id of "pdf".

(我要做的就是将div中ID为“ pdf”的任何内容打印为pdf。)

This must be done using JavaScript.

(这必须使用JavaScript来完成。)

The "pdf" document should then be automatically downloaded with a filename of "foobar.pdf"

(然后应使用文件名“ foobar.pdf”自动下载“ pdf”文档)

I've been using jspdf to do this, but the only function it has is "text" which accepts only string values.

(我一直在使用jspdf来执行此操作,但是它具有的唯一功能是仅接受字符串值的“文本”。)

I want to submit HTML to jspdf, not text.

(我想将HTML提交给jspdf,而不是文本。)

  ask by John Crawford translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

jsPDF is able to use plugins.

(jsPDF可以使用插件。)

In order to enable it to print HTML, you have to include certain plugins and therefore have to do the following:

(为了使其能够打印HTML,您必须包括某些插件,因此必须执行以下操作:)

  1. Go to https://github.com/MrRio/jsPDF and download the latest Version.

    (转到https://github.com/MrRio/jsPDF并下载最新版本。)

  2. Include the following Scripts in your project:

    (在您的项目中包括以下脚本:)

    • jspdf.js

      (jspdf.js)

    • jspdf.plugin.from_html.js

      (jspdf.plugin.from_html.js)

    • jspdf.plugin.split_text_to_size.js

      (jspdf.plugin.split_text_to_size.js)

    • jspdf.plugin.standard_fonts_metrics.js

      (jspdf.plugin.standard_fonts_metrics.js)

If you want to ignore certain elements, you have to mark them with an ID, which you can then ignore in a special element handler of jsPDF.

(如果要忽略某些元素,则必须用ID标记它们,然后可以在jsPDF的特殊元素处理程序中忽略该ID。)

Therefore your HTML should look like this:

(因此,您的HTML应该如下所示:)

<!DOCTYPE html>
<html>
  <body>
    <p id="ignorePDF">don't print this to pdf</p>
    <div>
      <p><font size="3" color="red">print this to pdf</font></p>
    </div>
  </body>
</html>

Then you use the following JavaScript code to open the created PDF in a PopUp:

(然后,使用以下JavaScript代码在弹出窗口中打开创建的PDF:)

var doc = new jsPDF();          
var elementHandler = {
  '#ignorePDF': function (element, renderer) {
    return true;
  }
};
var source = window.document.getElementsByTagName("body")[0];
doc.fromHTML(
    source,
    15,
    15,
    {
      'width': 180,'elementHandlers': elementHandler
    });

doc.output("dataurlnewwindow");

For me this created a nice and tidy PDF that only included the line 'print this to pdf'.

(对我而言,这创建了一个漂亮整洁的PDF,其中仅包含“将其打印为pdf”行。)

Please note that the special element handlers only deal with IDs in the current version, which is also stated in a GitHub Issue .

(请注意,特殊元素处理程序仅处理当前版本中的ID,这在GitHub Issue中也有说明。)

It states:

(它指出:)

Because the matching is done against every element in the node tree, my desire was to make it as fast as possible.

(因为匹配是针对节点树中的每个元素完成的,所以我希望使其尽可能快。)

In that case, it meant "Only element IDs are matched" The element IDs are still done in jQuery style "#id", but it does not mean that all jQuery selectors are supported.

(在那种情况下,这意味着“仅元素ID匹配”。元素ID仍以jQuery样式“ #id”完成,但这并不意味着支持所有jQuery选择器。)

Therefore replacing '#ignorePDF' with class selectors like '.ignorePDF' did not work for me.

(因此,用类选择器(如“ .ignorePDF”)替换“ #ignorePDF”对我不起作用。)

Instead you will have to add the same handler for each and every element, which you want to ignore like:

(相反,您将必须为每个元素添加相同的处理程序,您要忽略该元素,例如:)

var elementHandler = {
  '#ignoreElement': function (element, renderer) {
    return true;
  },
  '#anotherIdToBeIgnored': function (element, renderer) {
    return true;
  }
};

From the examples it is also stated that it is possible to select tags like 'a' or 'li'.

(从示例中还可以看出,可以选择诸如“ a”或“ li”之类的标签。)

That might be a little bit to unrestrictive for the most usecases though:

(不过,对于大多数用例来说,这可能是无限制的:)

We support special element handlers.

(我们支持特殊的元素处理程序。)

Register them with jQuery-style ID selector for either ID or node name.

(使用jQuery样式的ID选择器为ID或节点名注册它们。)

("#iAmID", "div", "span" etc.) There is no support for any other type of selectors (class, of compound) at this time.

((“ #iAmID”,“ div”,“ span”等。)目前不支持任何其他类型的选择器(类的复合)。)

One very important thing to add is that you lose all your style information (CSS).

(要添加的非常重要的一件事是您丢失了所有样式信息(CSS)。)

Luckily jsPDF is able to nicely format h1, h2, h3 etc., which was enough for my purposes.

(幸运的是,jsPDF能够很好地格式化h1,h2,h3等,足以满足我的目的。)

Additionally it will only print text within text nodes, which means that it will not print the values of textareas and the like.

(另外,它将仅打印文本节点内的文本,这意味着它将不打印textareas等的值。)

Example:

(例:)

<body>
  <ul>
    <!-- This is printed as the element contains a textnode -->        
    <li>Print me!</li>
  </ul>
  <div>
    <!-- This is not printed because jsPDF doesn't deal with the value attribute -->
    <input type="textarea" value="Please print me, too!">
  </div>
</body>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
...