I want modify html file for convert this to pdf.
Currently I convert an html file to pdf using "ITextRenderer".
Currently:
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- but more later I have the need to modify the html file before generating it as pdf, for this I think extract html file content and convert to string, then I replace some text on string 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- Then Replace tags in string from 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;
}
MAIN:
public static void main(String[] args) {
String stringFromHtml = new DocumentBLL().htmlFileToString();
String stringFromHtmlReplaced = new DocumentBLL().replaceHTMLcontent(stringFromHtml );
}
But now I do not know how to replace the new string with the old html string of the html file
You can first convert the whole html file into a string and do
String.replace("What I want to replace", "What it will be replaced with.");
Or if say you want to replace text1
and it's in a specific line , you can iterate through the file line by line (will be read as string) and look if there's text1 and implement the code I used above.
In addition, you can use this
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.