jsp to pdf in java with itext - java

I have searched for a solution but so far nothing gives me the answer i want. My question is how to convert an existing jsp page to pdf using itext possibly after clicking a button. Can someone give me a proper exaple.
All i can find is methods like this.
public String createHtmlSnippet(Movie movie) {
StringBuffer buf = new StringBuffer("\t<span class=\"title\">");
buf.append(movie.getMovieTitle());
buf.append("</span><br />\n");
buf.append("\t<ul>\n");
for (Country country : movie.getCountries()) {
buf.append("\t\t<li class=\"country\">");
buf.append(country.getCountry());
buf.append("</li>\n");
}
buf.append("\t</ul>\n");
buf.append("\tYear: <i>");
buf.append(movie.getYear());
buf.append(" minutes</i><br />\n");
buf.append("\tDuration: <i>");
buf.append(movie.getDuration());
buf.append(" minutes</i><br />\n");
buf.append("\t<ul>\n");
for (Director director : movie.getDirectors()) {
buf.append("\t\t<li><span class=\"director\">");
buf.append(director.getName());
buf.append(", ");
buf.append(director.getGivenName());
buf.append("</span></li>\n");
}
buf.append("\t</ul>\n");
return buf.toString();
}
I want to give the url and generate and download the pdf.

You can call a servlet on the button click. And in the servlet the you can use PDF Renderer. It converts HTML to PDF directly. although it has certain Restrictions like all tags should be closed like doing this <input/> wont work .
You would have to do <input></input>. But the output is amazing and fast and since it HTML you can change it easily. It internally uses iText. If you use iText directly then it would be a tedious process.
And your question should be HTML to PDF not JSP to PDf cause the JSP will get execute to produce some HTML in the end anyways
You entire HTML should be in the StringBuffer or String format.
Download from here
Update Code:
// First create a temporry file
File file = File.createTempFile("temp","pdf");
String html= "<HMTL><BODY>Hello</BODY></HTML>"; // HTML content
/* in your case it would be File f = new File("URL OF PAGE");
* */
// Write the contents intot he file.
PrintWriter printWriter = new PrintWriter(file);
printWriter.print(html); // Write String in Temp file
printWriter.close();
String s ="YourFile.pdf"; // Name of Actual PDf file
PDFRenderer.renderToPDF(file,s);// Second parameter is the actual PDF file
// The PDF is now created in the default location of you web application
// Now just read it and send it in the response.
File finalPDf = new File(s); // Reference to the newly created PDF file
PrintWriter out = response.getWriter();
response.setContentType("application/pdf");
IOUtils.copy(new InputStreamReader(new FileInputStream(s)), out);
// The above method just reads from the PDF file and puts the data in the response object
// IOUtils fully qualified name: org.apache.commons.io.IOUtils
// PDF Renderer fully qualified name: org.xhtmlrenderer.simple.PDFRenderer

I had same requirement Docx4j worked for me.It has lot of helpers docx4j documentation

Related

How to create a txt file with a String content and download that txt file

I am using java and struts. I have a scenario where there is 'Download' link in the page. After clicking on this link the control goes to the Action class, where I have String content which I need to write to a .txt file and then download that txt file.
Eventually whenever we click on the download link, we should be able to download a txt file having content a particular string.
I used below piece of code,
FileOutputStream outputStream = new FileOutputStream(fileNameWithDirectory);
outputStream.write(fileContentString.getBytes());
outputStream.close();
ActionForward forward = new ActionForward("doc/" + filename);
forward.setName(filename);
forward.setRedirect(true);
return forward;
Also I tried with FileWriter in place of FileOutputStream like,
FileWriter fileWriter = new FileWriter(fileNameWithDirectory);
fileWriter.write(fileContentString);
fileWriter.flush();
fileWriter.close();
But always instead of downloading the txt file, the control opens a new window where the String content is written.
Please suggest me, how would I able to download that .txt file.
You should add Content-Disposition: attachment to say browser, that it should download the file, not to open it.
See more details here
Also Struts has DownloadAction, you may use it as well.
You don't need to write the file and then redirect to it. You can set a http response header called Content-Disposition and then print your data into the http response body.
use it like this
response.addHeader("Content-Disposition", "Content-Disposition: attachment; filename=\""+filename+"\"");
of course this depends on which technology stack you're using.
Convert your text file to stream. and set content type as you wanted to download.
response.setContentType("application/pdf");
try {
// get your file as InputStream
InputStream is = ...;
// copy it to response's OutputStream
org.apache.commons.io.IOUtils.copy(is, convertedTextFiletoStream);
} catch (IOException ex) {
log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
throw new RuntimeException("IOError writing file to output stream");
}

Spring web application save file to server

I build a web application.
I would like to read files from server, then generate PDF file ( with itText) then save it to the server.
I don't know how to locate the files from the server then save the file to the server.
I read from my PC and write data to my PC perfectly.
The above code works properly but just on my computer not at server.
String jspPath = "C:\\Users\\dave\\Desktop\\eclipse\\project\\";
String fileName = "CV.txt";
InputStreamReader ir = new InputStreamReader(new FileInputStream(jspPath+filename), "UTF-8");
// Then generate the PDF with iText
//and
FileOutputStream fs = new FileOutputStream(jspPath+"generated.pdf");
PdfWriter pdfWriter = new PdfWriter(fs);
PdfDocument pdfdoc = new PdfDocument(pdfWriter);
JSP path references to my folder not the link with the generated pdf.
I would like :
put CV.txt to the server and read it.
Generate pdf ( it will work).
Save the generated PDF to server
A link to the generated PDF which i can download.
Thanks in Advance
Here are few things which might help you.
You can use FormData to pass text file from Frontend to Backend.
Use ajax post call to pass data.
you will have entire file on backend in the RequestContext parameter as FileItem object. you can start reading file using InputStreamReader.
than convert it into pdf file.
you can save pdf file to java temporary directory
String temporaryDir = System.getProperty("java.io.tmpdir");
this will return path for java temporary directory and you can delete this pdf file later
you will have to create ResponseBuilder with content-type='application/pdf' to download as a pdf file and return it to the UI. read this post
Hope this information helps you to solve your issue!

Append full PDF file to FOP PDF

I have an xml file already being created and rendered as a PDF sent over a servlet:
TraxInputHandler input = new TraxInputHandler(
new File(XML_LOCATION+xmlFile+".xml"),
new File(XSLT_LOCATION)
);
ByteArrayOutputStream out = new ByteArrayOutputStream();
//driver is just `new Driver()`
synchronized (driver) {
driver.reset();
driver.setRenderer(Driver.RENDER_PDF);
driver.setOutputStream(out);
input.run(driver);
}
//response is HttpServletResponse
byte[] content = out.toByteArray();
response.setContentType("application/pdf");
response.setContentLength(content.length);
response.getOutputStream().write(content);
response.getOutputStream().flush();
This is all working perfectly fine.
However, I now have another PDF file that I need to include in the output. This is just a totally separate .pdf file that I was given. Is there any way that I can append this file either to the response, the driver, out, or anything else to include it in the response to the client? Will that even work? Or is there something else I need to do?
We also use FOP to generate some documents, and we accept uploaded documents, all of which we eventually combine into a single PDF.
You can't just send them sequentially out the stream, because the combined result needs a proper PDF file header, metadata, etc.
We use the iText library to combine the files, starting off with
PdfReader reader = new PdfReader(/*String*/fileName);
reader.consolidateNamedDestinations();
We later loop through adding pages from each pdf to the new combined destination pdf, adjusting the bookmark / page numbers as we go.
AFAIK, FOP doesn't provide this sort of functionality.

JSP: I am doing an application in which i have to download ppt file

I am working on an application wherein I have to download a PPT file using a JSP page. I am using the following code, but it's not working.
<% try {
String filename = "file/abc.ppt";
// set the http content type to "APPLICATION/OCTET-STREAM
response.setContentType("APPLICATION/OCTET-STREAM");
// initialize the http content-disposition header to
// indicate a file attachment with the default filename
// "myFile.txt"
String disHeader = "Attachment Filename=\"abc.ppt\"";
response.setHeader("Content-Disposition", disHeader);
// transfer the file byte-by-byte to the response object
File fileToDownload = new File(filename);
FileInputStream fileInputStream = new
FileInputStream(fileToDownload);
int i;
while ((i=fileInputStream.read())!=-1)
{
out.write(i);
}
fileInputStream.close();
out.close();
}catch(Exception e) // file IO errors
{
e.printStackTrace();
}
%>
Can anybody solve this problem?
Not only the Content-Disposition header is incorrect, but you're incorrectly using JSP instead of a Servlet for this particular task.
JSP is a view technology. Everything outside the scriptlets <% %> will be printed to the response, including whitespace characters such as newlines. It would surely corrupt binary files.
You could trim the whitespace in the JSP file, but scriptlets are discouraged since a decade and nowadays considered bad practice. Raw Java code belongs in Java classes, not in JSP files. The real solution is to use a HttpServlet for this.
Create a class which extends HttpServlet, implement the doGet() method, move the Java code from the JSP file into this method, map this servlet on a certain url-pattern and your problem should disappear. You can find here a basic example of such a servlet.
Off the top there should be a semicolon in the Content-Disposition header ("attachment*;* filename ...)
You should also probably do a response.reset() before starting to set headers and stream. Internet Explorer has really strange rules about streaming files from secure sockets and won't work right if you don't clear the caching headers.

Using selenium.getBodyText() to capture HTML source, using Java, how can I save it into a HTML file locally?

This is probably a java noob question but here is my scenario:
using selenium, I captured the html source with getBodyText()
using java, I want to save the information from getBodyText() into a html file so I can review it later
I currently have getBodyText() stored as a String, here's the code:
String stored_report = selenium.getBodyText();
File f = new File("C:/folder/" + "report" + ".html");
FileWriter writer = new FileWriter(f);
writer.append(stored_report);
System.out.println("Report Created is in Location : " + f.getAbsolutePath())
writer.close();
Do I have to use FileReader? What do I need to do so the saved html file still shows the html format? (currently since it's stored as a string, the page shows up with everything appear on one line)
Thanks in advance!
Change to the following:
String stored_report = selenium.getBodyText();
File f = new File("C:/folder/" + "report" + ".html");
FileWriter writer = new FileWriter(f,true);
writer.write(stored_report);
System.out.println("Report Created is in Location : " + f.getAbsolutePath())
writer.close();
Your code looked sound except for appending operations. Using FileWriter(f,true) gives us appending operations on the write.
You only need the reader class if you want to read back the file you just wrote.
Update: Looks like selenium.getHtmlSource() exists and may do what you require. See This Post

Categories