2017-10-17 108 views
-1

我有一个表格,并需要有人填补帆布HTML文件(包括在画布上绘制)。
如何将HTML转换与内容填充形式到PDF文件后,保存在设备上的PDF?
我用Google搜索,但没有找到什么好的解决办法。转换HTML内容为PDF文件

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

回答

0

您可以使用iText

首先,你需要添加dependency-:

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

} 

编辑

下面的代码为我工作,以得到assestshtml文件 - :

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

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

+0

@tal你有没有试过这个 – UltimateDevil

+0

你的依赖有问题。安卓工作室告诉我一个错误消息:“无法解决:com.itextpdf:itextg:5.5.11”我尝试搜索jar文件,但它也是同样的问题。你有想法? – tal

+0

尝试使用编译'com.itextpdf:itextg:5.5.10'这一个为我工作 – UltimateDevil

0

我没有足够的信誉发表评论,但我想补充一点,为了得到UltimateDevil的回答工作,我需要添加以下gradle这个依赖关系:

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