1

I have to create PDF from my webView using PdfDocument on Android. https://developer.android.com/reference/android/graphics/pdf/PdfDocument.html The pdf is created well but it is only one page document.

// create a new document
PdfDocument document = new PdfDocument();

// create a page description
PageInfo pageInfo = new PageInfo.Builder(width,         
height, 1).create();

// start 1st page
Page page = document.startPage(pageInfo);
// draw something on the page
View content = myWebview;
content.draw(page.getCanvas());
// finish 1st page
document.finishPage(page);

// start 2nd page
Page page = document.startPage(pageInfo);
// draw something on the page
View content = someOtherWebview;
content.draw(page.getCanvas());
// finish 2nd page
document.finishPage(page);

// and so on...

FileOutputStream out;
try {
    out = new FileOutputStream(fileNameWithPath, false);
    // write the document content
     document.writeTo(out);

} catch (FileNotFoundException e) {
     e.printStackTrace();
} catch (IOException e) {
     e.printStackTrace();
}

// close the document
document.close();

How can I divide webview content in pages?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Makos
  • 11
  • 1
  • 6

1 Answers1

1

I am creating an android app that reads a file like a book, but instead of chopping it up and displaying one page at a time, I hide all but one of the sections and then just display the entire file.

So perhaps you could use a similar technique something like:
1. You can hide all of the webview with css
2. reveal one section
3. write to the PDF
4. hide the previous section
5. reveal the next etc.

In your text.html source file read by your webview, wrap each page in div tags like this:

<div id="page1" style="display:hidden;">
    Page 1 text
</div>
<div id="page2" style="display:hidden;">
    Page 2 text
</div>
<div id="page3" style="display:hidden;">
    Page 3 text
</div>

In your Java:

//First you have to enable Javascript
webView.getSettings().setJavaScriptEnabled(true);
//Then run this javascript which will find the first page and reveal it
webView.loadUrl("javascript:document.getElementById('page"+ 1 +"').style.display ='block';");
//reload Webview
webView.loadUrl("C:\Desktop\text.html");
//write to PDF
//repeat for page 2

hope this helps!

bradyGilley
  • 110
  • 3
  • 11