display pdf in browser using itext - pdf-generation

i have modify a pdf with itext using pdfstamper. my application now create and save a new pdf file. i want to dipslay the pdf directly in the browser. Here my actual code
public static void test07(){
try{
PdfReader reader = new PdfReader("c:\\temp\\file.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("c:\\temp\\new.pdf"));
AcroFields form = stamper.getAcroFields();
//fill the fields
stamper.close();
reader.close();
} catch (Exception e){
e.printStackTrace();
}
}
The question is: How should I modify this code and the servlet to display the pdf file in the browser?
I have already tried with ByteArrayOutputStream and response.getOutputStream but nothing.

You're in luck! The book iText in Action contains a chapter that describes how to do exactly what you need. It's fairly straightforward: set the right headers on your response, and stream to the servlet's output stream.
Here's the link: http://itextpdf.com/examples/iia.php?id=173

Related

loading a pdf in-browser from a file in the server file system?

How can I get a pdf located in a file in a server's directory structure to load in a browser for users of a Spring MVC application?
I have googled this and found postings about how to generate PDFs, but their answers do not work in this situation. For example, this other posting is not relevant because res.setContentType("application/pdf"); in my code below does not solve the problem. Also, this other posting describes how to do it from a database but does not show full working controller code. Other postings had similar problems that caused them not to work in this case.
I need to simply serve up a file (not from a database) and have it been viewable by a user in their browser. The best I have come up with is the code below, which asks the user to download the PDF or to view it in a separate application outside the browser. What specific changes can I make to the specific code below so that the user automatically sees the PDF content inside their browser when they click on the link instead of being prompted to download it?
#RequestMapping(value = "/test-pdf")
public void generatePdf(HttpServletRequest req,HttpServletResponse res){
res.setContentType("application/pdf");
res.setHeader("Content-Disposition", "attachment;filename=report.pdf");
ServletOutputStream outStream=null;
try {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(new File("/path/to", "nameOfThe.pdf")));
/*ServletOutputStream*/ outStream = res.getOutputStream();
//to make it easier to change to 8 or 16 KBs
int FILE_CHUNK_SIZE = 1024 * 4;
byte[] chunk = new byte[FILE_CHUNK_SIZE];
int bytesRead = 0;
while ((bytesRead = bis.read(chunk)) != -1) {outStream.write(chunk, 0, bytesRead);}
bis.close();
outStream.flush();
outStream.close();
}
catch (Exception e) {e.printStackTrace();}
}
Change
res.setHeader("Content-Disposition", "attachment;filename=report.pdf");
To
res.setHeader("Content-Disposition", "inline;filename=report.pdf");
You should also set the Content Length
FileCopyUtils is handy:
#Controller
public class FileController {
#RequestMapping("/report")
void getFile(HttpServletResponse response) throws IOException {
String fileName = "report.pdf";
String path = "/path/to/" + fileName;
File file = new File(path);
FileInputStream inputStream = new FileInputStream(file);
response.setContentType("application/pdf");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "inline;filename=\"" + fileName + "\"");
FileCopyUtils.copy(inputStream, response.getOutputStream());
}
}

write file into spring boot folder

my spring boot project structure is like this
src
|-main
|--|-java
|--|-resources
static
|-css
|-images
|-js
now I want to write a file into the static/images folder
I tried to new File like
BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File("static/images")));it will throw "No such file or directory" exception
but in other html file I can get the js by "js/jsFile.js"
new File("static/images") is right
I used new File("/static/images") so I got an Exception
I was in the situation where using Spring Boot I had to save the image into one directory which is accessed statically.
Below code worked perfect
byte[] imageByteArray ....
String fileName = "image.png";
String fileLocation = new File("static\\images").getAbsolutePath() + "\\" + fileName;
FileOutputStream fos = new FileOutputStream(fileLocation);
fos.write(imageByteArray);
fos.close();
Hope it helped.
#zhuochen shen is correct.
The thing is to happen me is Eclipse doesn't show write file. So I looked at file explore. File is writing correctly.
try {
Path path=Paths.get("static/images/"+productDto.getImage().getOriginalFilename());
Files.write(path,productDto.getImage().getBytes());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
enter image description here
enter image description here

Replace Image with out user noticing

I'm using JSF 2.1.7 + Prime Faces + Prime Faces Mobile.
I have a page that references a image:
<img src="/charts/chart1.png"/>
There's a separate background process that runs to update chart1.png every 2 minutes. (It gets the image from a particular online url). Here is the code I use to save the image:
public static String saveImage(final String strurl, final String imageFileName){
//assume the url for the image is valid
try {
URL url = new URL(strurl);
HttpURLConnection conn = (HttpURLConnection )url.openConnection();
conn.setConnectTimeout(1000); //1 sec timeout
conn.connect();
File file = new File(imageFileName);
BufferedImage image = ImageIO.read(conn.getInputStream());
ImageIO.write(image, "png", file);
return file.getAbsolutePath();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
ImageIO.write will delete the existing image file and write out a new one. I believe the above will result in a few milliseconds where the image file is not available, and hence the web user will not be able to see the image.
My questions are:
1) Is it true that there will be a time where the image is temporarily unavailable?
2) And if that is the case, what is a possible solution to fix this, so that user will always have a available image?
Thanks in advance. =)
Heres what i would do
1) First instead of replacing the image, i create a new image chart2.png
2)Then I would change the url in the IMG tag to point to a Servlet,
say
and in that servlet which will be mapped to /charts/showchart
,
And in the servlet i would check for latest available PNG , and stream it as response.
This way you customize how or what image you show.

Generate a pdf file and send after querying database for a pass mark

My project is almost done, and thanks to stackoverflow. Now that I have managed to capture Users details and their certificates, I am looking for a way to generate pdf which I will send to those who passed.
I am not looking for the code at the moment. I have an asp.net mvc 3 application which shows Certificates details for my students. Now I want the certificates to be generated then sent by email, all this automated.
First I would like help on how I can generate a pdf from database values and sending the generated pdf wont be a problem.
Using iTextSharp, this code will create and serve a PDF:
public FileStreamResult DownloadPDF()
{
MemoryStream workStream = new MemoryStream();
using(Document document = new Document())
{
PdfWriter.GetInstance(document, workStream).CloseStream = false;
document.Open();
document.SetPageSize(PageSize.LETTER);
document.SetMargins(12, 12, 8, 7);
document.NewPage();
// Create a new Paragraph object with the text, "Hello, World!"
var welcomeParagraph = new Paragraph("Hello, World!");
// Add the Paragraph object to the document
document.Add(welcomeParagraph);
// This is where your data would go
document.Close();
}
workStream.Position = 0;
FileStreamResult fileResult = new FileStreamResult(workStream, "application/pdf");
fileResult.FileDownloadName = "test.pdf";
return fileResult;
}
For more information see Creating PDF Documents with ASP.NET and iTextSharp
There are a lot of tutorials online, but this should get you started.

How can I insert an image with iTextSharp in an existing PDF?

I have an existing PDF and I can use FdFWriter to input to text boxes. It works well. Now I have an image. I have read the documentation and looked at many examples but they all create new documents and insert an image. I want to take an existing PDF and insert an image into either an image field or as the icon image of a button. I have tried but it corrupts the document.
I need to be able to take an existing document and put an image on it. I do not want to open, read, replace, and delete the original. This original changes and the name "original" only means the source file in this context. There are many PDF files like this that need an image.
Thank you for any help.
Edit - I am very thankful for the code below. It works great, but the problem for me is that the existing PDF has digital signatures on it. When the document is copied like this (into result.pdf) those signatures, while still present, have a different byte count or other item that is corrupted. This means the signatures, while they show up on result.pdf, have an icon next to them that state "invalid signature."
In case it matters I am using a Topaz signature pad to create my signatures, which has it's own security. Merely copying the PDF will not corrupt it but the process below will.
I am trying to put the image on the existing document, not a copy of it, which in this case matters.
Also, by signature, I mean handwritten, not pin numbers.
Thank you again.
EDIT - Can PdfSignatureAppearance be used for this?
EDIT - I seem to be able to do it with:
var stamper = new PdfStamper(reader, outputPdfStream,'1',true);
If you want to change the contents of an existing PDF file and add extra content such as watermarks, pagenumbers, extra headers, PdfStamper is the object you need. I have successfully used the following code to insert an image into an existing pdf file to a given absolute position:
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
class Program
{
static void Main(string[] args)
{
using (Stream inputPdfStream = new FileStream("input.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream inputImageStream = new FileStream("some_image.jpg", FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream outputPdfStream = new FileStream("result.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
var pdfContentByte = stamper.GetOverContent(1);
Image image = Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(100, 100);
pdfContentByte.AddImage(image);
stamper.Close();
}
}
}
When you insert the image you have the possibility to resize it. You can take a look at transformation matrix in the iTextSharp documentation.
Here is a similar example whichi inserts an image on the page using the stamper:
Gmane iTex Mailing List Post
I could solve my problem by simply adding following lines to my signing code to add image
var image = iTextSharp.text.Image.GetInstance(#"C:\Users\sushil\Documents\sansign.jpg");
appearance.Acro6Layers = true;
appearance.SignatureGraphic = image;
appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
As I was signing document with visible digital signature , now I can have both image and digital signature properties side by side
in the .net core6 that uses DDD try this declare class in Infrastructure Layer
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
public async Task<string> SignatureToPdf(string pathPdfFile, string
pathSignatureImage, string pathOutputName)
{
var webRootPath = hostingEnvironment.ContentRootPath;
if (!File.Exists(Path.Combine(webRootPath, pathPdfFile))) return
null;
await using Stream inputPdfStream =
new FileStream(Path.Combine(webRootPath, pathPdfFile),
FileMode.Open, FileAccess.Read, FileShare.Read);
await using Stream inputImageStream =
new FileStream(Path.Combine(webRootPath, pathSignatureImage), FileMode.Open, FileAccess.Read, FileShare.Read);
await using Stream outputPdfStream =
new FileStream(Path.Combine(webRootPath, pathOutputName),
FileMode.Create, FileAccess.Write, FileShare.None);
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
var pdfContentByte = stamper.GetOverContent(1);
var image = Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(100, 100);
pdfContentByte.AddImage(image);
stamper.Close();
return "ok";
}
pdftk can do this. It's not a library but you can easily call it from your code as a .exe.
See stamp and background commands:
http://www.pdflabs.com/docs/pdftk-man-page/
ref: How to do mail merge on top of a PDF?

Resources