tal
tal

Reputation: 295

Converting Html content to a pdf file

I have html file with form and canvas that need to filling by someone(include the draw on the canvas).
How to convert the html with the content after filling form to PDF file and save the PDF on the device?
I googled, but didn't find any good solution.

Update: All the html,css, js files are in assest folder.

Upvotes: 1

Views: 6250

Answers (2)

Dholakiya Madhuri
Dholakiya Madhuri

Reputation: 57

https://github.com/blink22/react-native-html-to-pdf/blob/master/android/src/main/java/android/print/PdfConverter.java

PdfConverter converter = PdfConverter.getInstance();
File file = new File(Environment.getExternalStorageDirectory().toString(), "file.pdf");
String htmlString = "html code here";
converter.convert(getContext(), htmlString, file);

Upvotes: 1

UltimateDevil
UltimateDevil

Reputation: 2847

You can use iText

First you need to add dependency-:

dependencies {
compile 'com.itextpdf:itextg:5.5.11'
}

Sample code

private void createPDF (String pdfFilename){

  //path for the PDF file to be generated
  String path = "docs/" + pdfname;
  PdfWriter pdfWriter = null;

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

  try {

   //get Instance of the PDFWriter
   pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(path));

   //document header attributes
   document.addAuthor("betterThanZero");
   document.addCreationDate();
   document.addProducer();
   document.addCreator("MySampleCode.com");
   document.addTitle("Demo for iText XMLWorker");
   document.setPageSize(PageSize.LETTER);

   //open document
   document.open();

   //To convert a HTML file from the filesystem
   //String File_To_Convert = "docs/SamplePDF.html";
   //FileInputStream fis = new FileInputStream(File_To_Convert);

   //URL for HTML page
   URL myWebPage = new URL("http://demo.mysamplecode.com/");
   InputStreamReader fis = new InputStreamReader(myWebPage.openStream());

   //get the XMLWorkerHelper Instance
   XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
   //convert to PDF
   worker.parseXHtml(pdfWriter, document, fis);

   //close the document
   document.close();
   //close the writer
   pdfWriter.close();

  }   

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

 }

EDIT

Below code is working for me to get html file from assests folder -:

InputStream is = getAssets().open("test.html");
InputStreamReader fis =  new InputStreamReader(is);

You can change

URL myWebPage = new URL("http://demo.mysamplecode.com/");
InputStreamReader fis = new InputStreamReader(myWebPage.openStream());

to

InputStream is = getAssets().open("test.html");
InputStreamReader fis =  new InputStreamReader(is);

May, Help you. Happy Coding :)

Upvotes: 1

Related Questions