1

I am trying to generate a PDF from a HTML string using PdfDocument:

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. How i do this? I don't found in stackoverflow.com or Google how do this with the native class PDFDOCUMENT

Dayron Cediel
  • 87
  • 2
  • 7

2 Answers2

6

This class does what you are looking for.

But to compile, it must be in package ".../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.
Islam Salah
  • 953
  • 11
  • 22
1

react-native-html-to-pdf works great and has zero iText dependencies.

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 )
  • Renders <img /> using base64 or local files ( make sure you close the img tag )
  • CSS style works great.
  • You can Control page breaks from your HTML.

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

I forked it and added page size and orientation options to Android. I plan to do the same to iOS but it currently has width and height options that can accomplish this same thing.

This is a cross-platform Android and iOS React Native library.

Look in the Android directory if you just need the Java.

Ed of the Mountain
  • 5,219
  • 4
  • 46
  • 54
  • Not sure where you see that it has zero iText dependencies. It says "The android module pulls in iText to convert html to pdf. A license is required for commercial use." – Casey Hancock Apr 04 '18 at 05:28
  • 2
    The README is out of date. Read the Java source instead. https://github.com/christopherdro/react-native-html-to-pdf/blob/master/android/src/main/java/android/print/PdfConverter.java – Ed of the Mountain Apr 06 '18 at 17:14
  • 1
    See commit comment that "iText has been removed". https://github.com/christopherdro/react-native-html-to-pdf/commit/5d4092b149f25e85117c8060b1d4968f35829407 – Ed of the Mountain Apr 06 '18 at 17:18