2017-10-17 111 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'