我想修改 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/