1

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

Lokesh Kumar Gaurav
  • 726
  • 1
  • 8
  • 24
Alonso Contreras
  • 605
  • 2
  • 12
  • 29
  • Possible duplicate of [Java Replace Line In Text File](https://stackoverflow.com/questions/20039980/java-replace-line-in-text-file) – Rei Brown Feb 01 '18 at 05:34

1 Answers1

0

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();
Rei Brown
  • 185
  • 9