How can I convert HTML
string (created on the fly) to PDF
only using native PrintedPdfDocument
(API
19 or higher)? I look for the solution in which I do not need to add any external libraries.
Asked
Active
Viewed 1,049 times
2
-
I am not aware of any direct way to get a PDF from HTML without using libraries. While Android 4.4+ is capable of printing HTML via a `WebView`, there is no direct way for you to get the PDF that might be used as the printed content. – CommonsWare Dec 11 '15 at 16:48
-
WebView does not solve my problem because even though I can easily generate PDF from WebView content, I can only do it after explicitely displaying it on the screen. If after adding webView.setVisibility(View.GONE); the app would work, I could use it in my case. But adding GONE causes that no content is able to be captured. I am not sure if you can understand me – Annabelle Dec 11 '15 at 16:55
1 Answers
0
If the HTML is very limited, you can try TextView
and some HTML-to-Spanned
converter (e.g., Html.fromHtml()
).
Or, as I noted in comments, you can use WebView
, though you indicate that it does not meet your business requirements, and I am not sure that you can get to the PDF anyway.
Otherwise, your only library-free option is to send the HTML to a server, one that can return to you a PDF.

CommonsWare
- 986,068
- 189
- 2,389
- 2,491
-
Please read my comment above. I need a solution in which I can generate PDF in a background (or e.g. with visibility GONE) – Annabelle Dec 11 '15 at 17:03
-
@Annabelle: "Please read my comment above" -- please read my answer above, specifically "though you indicate that it does not meet your business requirements, and I am not sure that you can get to the PDF anyway". At least with `TextView`, you should be able to create one that is not attached to the view hierarchy, but that you manually `measure()` and `layout()` to your desired size, then use that with `PdfDocument`. Otherwise, your choices are libraries, servers, or writing your own HTML parser and implementing your own low-level `Canvas` drawing code. – CommonsWare Dec 11 '15 at 17:11