java - 如何替换文本 html 以转换为 pdf? java

标签 java string pdf tags document

我想修改 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-但后来我需要在将 html 文件生成为 pdf 之前对其进行修改,为此我认为提取 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字符串替换新字符串

最佳答案

您可以先将整个 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();

关于java - 如何替换文本 html 以转换为 pdf? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48554550/

相关文章:

ios - 将 String 转换为 NSDate 但仍然无法访问 dateByAddingTimeInterval 方法

excel - 与字符串比较时如何使用 "TypeOf ___ is ___ Then "

javascript - 如何在 Node js中创建pdf文件

java - 处理与 JavaFx 与 Griffon 的比较

java - 测试用例失败时使用 EasyTest 时出现 ParameterizedAssertionError

java - 映射条目出现在 HashMap.entrySet() 中,但不在内部 HashMap.table 中

java - HBase Java Api 卡在 put()

c# - 将字节数组转换为数字字符串 [c#]

javascript - (Adobe Acrobat CC) if 计算中的语句不起作用

c++ - 从PDF中提取第一行文本