android - 将 Html 内容转换为 pdf 文件

标签 android html pdf

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

更新:所有的html、css、js文件都在assest文件夹下。

最佳答案

您可以使用 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();
  }       

 }

编辑

下面的代码让我从 assests 文件夹中获取 html 文件 -:

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

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

关于android - 将 Html 内容转换为 pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46787546/

相关文章:

java - 如何确定已弃用的权限?

javascript - 动态更新 SVG

android - Android中使用百度API显示 map

Android NYTimes 滑动动画/手势

javascript - Panzoom - 如何禁用拖动选项?

javascript - 防止 Angular Ng-Click 上的区域标签页面重新加载

linux - 追踪器还是召回器?

swift - 在 macOS 上使用 Swift 在 PDF 上绘图

ios - drawInRect 不适用于 PDF

android - 错误 : Unresolved reference: DaggerAppComponent