简体   繁体   English

使用PdfDocument将HTML格式化为PDF

[英]Html to PDF using PdfDocument

I am trying to generate a PDF from a HTML string using PdfDocument: 我正在尝试使用PdfDocument从HTML字符串生成PDF:

https://developer.android.com/reference/android/graphics/pdf/PdfDocument.html https://developer.android.com/reference/android/graphics/pdf/PdfDocument.html

String example: 字符串示例:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
            <title>Example</title>
        </head>
        <body>
            <h1>Hello</h1>
        </body>
    </html>

I know how to generate a PDF files from a WebView, but not from a string HTML. 我知道如何从WebView生成PDF文件,但不是从字符串HTML生成。 How i do this? 我怎么做的? I don't found in stackoverflow.com or Google how do this with the native class PDFDOCUMENT 我没有在stackoverflow.com或Google中找到如何使用本机类PDFDOCUMENT

This class does what you are looking for. 课程可以满足您的需求。

But to compile, it must be in package ".../java/android/print/" 但要编译,它必须在包“... / java / android / print /”

Here is a simple code example : 这是一个简单的代码示例:

PdfConverter converter = PdfConverter.getInstance();
File file = new File(Environment.getExternalStorageDirectory().toString(), "file.pdf");
String htmlString = "<html><body><p>WHITE (default)</p></body></html>";
converter.convert(getContext(), htmlString, file);
// By now the pdf has been printed in the file.

你必须使用像itext这样的外部库

react-native-html-to-pdf works great and has zero iText dependencies. react-native-html-to-pdf效果很好, 没有 iText依赖。

https://github.com/christopherdro/react-native-html-to-pdf https://github.com/christopherdro/react-native-html-to-pdf

  • Renders SVG <svg> ( Very easy to reuse svg code from Google Material Icons in an HTML document ) 渲染SVG <svg> (非常容易在HTML文档中重用Google Material Icons中的svg代码)
  • Renders <img /> using base64 or local files ( make sure you close the img tag ) 使用base64或本地文件渲染<img /> (确保关闭img标记)
  • CSS style works great. CSS风格很棒。
  • You can Control page breaks from your HTML. 您可以从HTML控制分页符。

    <p style="page-break-before: always;" />

I forked it and added page size and orientation options to Android. 我将它分叉并向Android添加了页面大小和方向选项。 I plan to do the same to iOS but it currently has width and height options that can accomplish this same thing. 我计划对iOS做同样的事情,但它目前有宽度和高度选项,可以完成同样的事情。

This is a cross-platform Android and iOS React Native library. 这是一个跨平台的Android和iOS React Native库。

Look in the Android directory if you just need the Java. 如果您只需要Java,请查看Android目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM