将Html内容转换为pdf文件

时间:2017-10-17 10:05:07

标签: android html pdf

我的html文件包含需要由某人填写的表单和画布(包括画布上的绘图) 如何在填写表格后将内容转换为PDF文件,并将PDF保存在设备上?
我用谷歌搜索,但没有找到任何好的解决方案。

更新:所有html,css,js文件都在assest文件夹中。

3 个答案:

答案 0 :(得分:2)

I don't have enough reputation to comment, but I would like to add that, in order to get UltimateDevil's answer to work, I needed to add the following gradle dependencies:

compile 'com.itextpdf:itext-pdfa:5.5.10'
compile group: 'com.itextpdf.tool', name: 'xmlworker', version: '5.5.10'

答案 1 :(得分:1)

答案 2 :(得分:0)

您可以使用 iText

首先,您需要添加依赖项 - :

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

示例代码

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();
  }       

 }

修改

以下代码可供我从 html 文件夹中获取assests文件 - :

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

您可以更改

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

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

五月,帮助你。快乐编码:)