1

I'm trying to convert WebView's text content to PDF. Using the code below.

PdfDocument.Page page = document.StartPage(new PdfDocument.PageInfo.Builder(webpage.Width, webpage.Height, 1).Create());
webpage.Draw(page.Canvas);

PDF is properly generated but I can't select text from that PDF. Its like WebView content but converted into an image.

But if I try to print same WebView from the print menu and save it as PDF text selection is working and size of the pdf is smaller.

So how can I create PDF from WebView where text is also selectable.

Eg. of text selection.

Sample UI action

Some random IT boy
  • 2,687
  • 2
  • 11
  • 28
Code OverFlow
  • 743
  • 12
  • 26

2 Answers2

1

What you did is printing the web page as an image to the PDF canvas - that's why the size is larger, and you cannot select text. Because the text is not present there as a text object, but as an image. The reason for this, is that you draw the webview (and not the webpage) to the PDF canvas. That is just like outputting the view itself as a bitmap to the PDF.

What you might want to do is to use an XHTML to PDF rendering library, like iText or Flying Saucer to properly render the XHTML webpage (and not the webview!) to a PDF.

persicsb
  • 316
  • 1
  • 2
1

You can use iText library for this, add this dependency in gradle

compile 'com.itextpdf:itextg:5.5.10'

Now convert the webview's text to pdf like this

try {
            File mFolder = new File(getExternalFilesDir(null) + "/sample");
            File imgFile = new File(mFolder.getAbsolutePath() + "/Test.pdf");

            if (!mFolder.exists()) {
                mFolder.mkdir();
            }
            if (!imgFile.exists()) {
                imgFile.createNewFile();
            }

            String webviewText = "<html><body>Your  webview's text content </body></html>";
            OutputStream file = new FileOutputStream(imgFile);

            Document document = new Document();
            PdfWriter.getInstance(document, file);
            document.open();
            HTMLWorker htmlWorker = new HTMLWorker(document);
            htmlWorker.parse(new StringReader(webviewText));
            document.close();
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
Navneet Krishna
  • 4,667
  • 5
  • 21
  • 40