【问题标题】:How to replace text html for convert to pdf ? Java如何替换文本html以转换为pdf?爪哇
【发布时间】:2018-02-01 02:42:28
【问题描述】:

我想修改 html 文件以将其转换为 pdf。

目前我使用“ITextRenderer”将 html 文件转换为 pdf。

目前:

  OutputStream out = new FileOutputStream(htmlFileOutPutPath);

   //Flying Saucer 
    ITextRenderer renderer = new ITextRenderer();

    renderer.setDocument(htmlFilePath);
    renderer.layout();
    renderer.createPDF(out);

    out.close();
    //This success!! html file to pdf generated!

1-但后来我需要在将其生成为pdf之前修改html文件,为此我认为提取html文件内容并转换为字符串,然后我替换字符串html上的一些文本:

public String htmlFileToString() throws IOException {

    StringBuilder contentBuilder = new StringBuilder();
    String path = "C:/Users/User1/Desktop/to_pdf_replace.html";

    BufferedReader in = new BufferedReader(new FileReader(path));

    String str;
    while ((str = in.readLine()) != null) {
        contentBuilder.append(str);
    }

    in.close();

    String content = contentBuilder.toString();

    return content;
}

2- 然后从 html 中替换字符串中的标签

public String replaceHTMLcontent(String strSource)
{

    String name = "Ana";
    String age = "23";
    String html = strSource;

    strSource = strSource.replace("##Name##", name);
    strSource = strSource.replace("##Age##", age);
    //## ## -> are my html custom tags to replace

    return strSource;

}

主要:

public static void main(String[] args) {

    String stringFromHtml = new DocumentBLL().htmlFileToString();
    String stringFromHtmlReplaced =  new DocumentBLL().replaceHTMLcontent(stringFromHtml );


}

但是现在不知道怎么用html文件的旧html字符串替换新字符串

【问题讨论】:

标签: java string pdf tags document


【解决方案1】:

你可以先把整个html文件转成字符串再做

String.replace("What I want to replace", "What it will be replaced with.");

或者如果说你想替换text1并且它在一个特定的,你可以逐行遍历文件(将被读取为字符串)看看是否有 text1 并实现我上面使用的代码。

另外,你可以用这个

BufferedReader file = new BufferedReader(new FileReader("myFile.html"));
String line;
StringBuffer buffer = new StringBuffer();
while (line = file.readLine()) {
 buffer.append(line);
 buffer.append('\n');
    }
    String input = buffer.toString();

    file.close();
input = input.replace("What I want to insert into", "What I (hi there) want to insert into");

FileOutputStream out = new FileOutputStream("myFile.html");
out.write(inputStr.getBytes());
out.close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    • 2015-10-23
    • 2011-06-24
    相关资源
    最近更新 更多