For my use, I created a PDF file using flying-saucer library. It was a legacy HTML so I cleaned out the XHTML using HTMLCleaner library.
After this I serialize the XML as string then pass it to the iText module of flying-saucer to render it and subsequently create the PDF.
This PDF I place it in the OutputStream. After the response is committed I get a dialog asking to save or open it. However it does not get saved as PDF file. I have to right-click and open it in Adobe or any PDF reader.
How do I make it display in the PDF reader. And make the file be saved as .pdf file. What would be an effective and user-friendly way to handle this issue? Help as always will be greatly appreciated!
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringBufferInputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.DomSerializer;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.PrettyXmlSerializer;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XmlSerializer;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.resource.XMLResource;
public class MyPDF extends HttpServlet {
public MyPDF() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/pdf");
String html = request.getParameter("source");
try
{
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties props = cleaner.getProperties();
TagNode node = cleaner.clean(html);
//String content = "<" + node.getName() + ">" + cleaner.getInnerHtml(node) + "</" + node.getName() + ">";
//System.out.println("content " +content);
OutputStream os = response.getOutputStream();
System.out.println("encoding " +response.getCharacterEncoding());
final XmlSerializer xmlSerializer = new PrettyXmlSerializer(props);
final String html1 = xmlSerializer.getAsString(node);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html1);
renderer.layout();
renderer.createPDF(os);
os.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public void init() throws ServletException {
}
}
Your MIME type is incorrect for PDF. It should be application/pdf.
Change
response.setContentType("text/pdf");
to
response.setContentType("application/pdf");
See https://www.rfc-editor.org/rfc/rfc3778 for the RFC for the PDF MIME type.
Edit: Totally overlooked the "Save as .pdf" question.
You'll also need to add something like:
response.setHeader("content-disposition", "attachment; filename=yourFileName.pdf");
to tell the browser what the default file name should be.
Related
I am new to web programming. I am using this simple code in my get method
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
out.println( "<html><head><title>Guest Book</title></head><body>" );
out.println(" </body></html> ");
I am getting the below error while clicking on run on server
enter image description here
Note: When i removed the html code, the servlet is working fine.Is it my Html code problem or any tomcat sevrver issue.
The servlet is in my package cs3220homework and servlet name is #WebServlet("/MainFolder").
I tried everywhere to look for the issue and i was not able to find it.If its duplicate please let me know.
Thanks for your reply
Harminder
Its working fine. App is named Test and Servlet class is also named Test. This is the url http://localhost:8080/Test/Test
package foo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Test")
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
out.println( "<html><head><title>Guest Book</title></head><body>" );
out.println(" </body></html> ");
}
}
I want to copy the contents of an uploaded file to a text file on my local.
The important thing is- I already have a file on my system named "Data" and I want to append the contents of uploaded file in "Data".
I have successfully copied the contents of the uploaded file but facing issue in appending the data.
Below is my Servlet file:
package pack;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUploadHandler extends HttpServlet {
private final String UPLOAD_DIRECTORY = "D:/Data Repository.txt";
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//process only if its multipart content
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
item.write(new File(UPLOAD_DIRECTORY));
}
}
//File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex)
{
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}else{
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
Can something be added or modified in the below statement so that it would append the data to the existing file rather than creating a new file every time and copying its content?
item.write(new File(UPLOAD_DIRECTORY));
I have written a code which will fetch me a html contents of the page as response , I am using HTML Unit to do so . But I am getting error's for some specific urls like
[https://communities.netapp.com/welcome][1]
For first page i am able to retrieve the contents . But when i dont the content which we get using load more button .
Here's my code:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.MalformedURLException;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class Sample {
public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException {
String url = "https://communities.netapp.com/welcome";
WebClient client = new WebClient(BrowserVersion.INTERNET_EXPLORER_9);
client.getOptions().setJavaScriptEnabled(true);
client.getOptions().setRedirectEnabled(true);
client.getOptions().setThrowExceptionOnScriptError(true);
client.getOptions().setCssEnabled(true);
client.getOptions().setUseInsecureSSL(true);
client.getOptions().setThrowExceptionOnFailingStatusCode(false);
client.setAjaxController(new NicelyResynchronizingAjaxController());
HtmlPage page = client.getPage(url);
Writer output = null;
String text = page.asText();
File file = new File("D://write6.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
System.out.println("Your file has been written");
// System.out.println("as Text ==" +page.asText());
// System.out.println("asXML == " +page.asXml());
// System.out.println("text content ==" +page.getTextContent());
// System.out.println(page.getWebResponse().getContentAsString());
}
}
Any suggestion ?
As i understand from your question you have a button on which you have to press.
Please look at: http://htmlunit.sourceforge.net/gettingStarted.html
You have there an example of submitting a form.
This should be very similar here
I'm trying create pdf in java with google app engine but it doesn't work yet:
#SuppressWarnings("serial")
public class GuestbookServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("application/pdf");
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
document.open();
document.add(new Paragraph("Hello World"));
document.close();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is the error:
HTTP ERROR 500
Problem accessing /guestbook. Reason:
com/itextpdf/text/DocumentException
Caused by:
java.lang.NoClassDefFoundError: com/itextpdf/text/DocumentException
I have read the incompatibility with java.awt and java.nio with google appengine. But I don't know how to do it. Is there any special version of itext to google app engine? Or do you know any clue that can help me?
Yes, there's a GAE version of iText. See http://lowagie.com/iPadSchools to watch a demo. The GAE port is distributed by iText Software. There's no link to get it online.
package mx.gob.campeche.sit.web.reportes;
import java.io.IOException;
import java.io.OutputStream;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import mx.gob.campeche.sit.doc.recibo_oficial.ReciboOficial;
#WebServlet("/reciboOficial")
public class ReporteReciboOficialServlet extends HttpServlet {
#Inject
ReciboOficial reciboOficial;
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpServletRequestWrapper srw = new HttpServletRequestWrapper(request);
String folio = "";
if (request.getParameterMap().containsKey("folio")) {
folio = request.getParameter("folio");
System.out.println("contenido" + folio);
}else
if (request.getParameterMap().containsKey("numero")) {
folio = request.getParameter("numero");
System.out.println("contenido" + folio);
}else{
throw new ServletException("No ingreso parametro");
}
byte[] pdfData = reciboOficial.crearReciboOFicialCajas(folio, srw.getRealPath(""));
response.setContentType("application/pdf");
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "inline; filename=\"" +"samplePDF2.pdf" +"\"");
OutputStream output = response.getOutputStream();
output.write(pdfData);
output.close();
}
this is small example, this help
I have a servlet in which I first download a pdf in from http://www.cbwe.gov.in/htmleditor1/pdf/sample.pdf upload it's content on my blobstore and when a user sends a get request in browser a blob will be downloaded in browser, but instead of downloading it's showing data in some other format. Here is my code of servlet:
package org.ritesh;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import javax.servlet.http.*;
import org.apache.commons.io.IOUtils;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileWriteChannel;
#SuppressWarnings("serial")
public class BlobURLServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
FileService fileService = FileServiceFactory.getFileService();
// Create a new Blob file with mime-type "text/plain"
String url="http://www.cbwe.gov.in/htmleditor1/pdf/sample.pdf";
URL url1=new URL(url);
HttpURLConnection conn=(HttpURLConnection) url1.openConnection();
String content_type=conn.getContentType();
InputStream stream =conn.getInputStream();
AppEngineFile file = fileService.createNewBlobFile("application/pdf");
file=new AppEngineFile(file.getFullPath());
Boolean lock = true;
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
// This time we write to the channel directly
String s1="";
String s2="";
byte[] bytes = IOUtils.toByteArray(stream);
writeChannel.write(ByteBuffer.wrap(bytes));
writeChannel.closeFinally();
BlobKey blobKey = fileService.getBlobKey(file);
BlobstoreService blobStoreService = BlobstoreServiceFactory.getBlobstoreService();
blobStoreService.serve(blobKey, resp);
}
}
I deploy this servlet on onemoredemo1.appspot.com. Please open this url and notice when u click on BlobURL servlet it's showing content instead of showing downloading dialog. What modification should I do in my code so it shows download dialog in browser?
Look here:
resp.setContentType("text/plain");
You've said that the content is plain text, when it's not. You need to set the Content-Disposition header appropriately as an attachment, and set the content type to application/pdf.
Additionally, if you're going to serve binary content, you shouldn't also use the writer (which you're writing "Hello, world" with).
If you change your first couple of lines to:
resp.setContentType("application/pdf");
resp.setHeader("Content-Disposition", "attachment;filename=sample.pdf");
you may find that's all that's required.