How do I display a PDF onto a JSF page - html

I want to display a PDF file onto my JSF page, I have check this how to display a pdf document in jsf page in iFrame, but I dont want to display it on an iframe(since it will generate scroll bar). I just want to display the pdf onto a page like an image and able to give a width and height for it.
EDIT Hi BalusC. I still cant be able to display the pdf inline. Here is my code.
#WebServlet(name = "pdfHandler", urlPatterns = {"/pdfHandler/*"})
public class pdfHandler extends HttpServlet {
private static final int DEFAULT_BUFFER_SIZE = 10240;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String requestedFile = request.getPathInfo();
File file = new File("/Users/KingdomHeart/Downloads/Test/pdf/" + requestedFile);
response.reset();
response.setContentType("application/pdf");
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try{
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while((length = input.read(buffer)) > 0){
output.write(buffer, 0, length);
}
}finally{
output.close();
input.close();
}
}
...
}
It still prompt me to download the pdf file. The pdf file that get downloaded to my computer is the correct pdf file btw. Can u spot anything wrong?

There's not really another way (expect from HTML <object> tag which would have the same "problems"), but you can just give the <iframe> a fixed size and disable the scrolling as follows:
<iframe src="foo.pdf" width="600" height="400" scrolling="no"></iframe>
If you also want to hide the (default) border, add frameBorder="0" as well.

You should take a look at ICEpdf, it creates an image on the server side, gives zooming, and other controls (demo).

Try going into Adobe Reader, and under the Options dialog there are web settings where you can indicate that you always want PDF type documents to open within the browser.
This is unfortunately a client side fix and doesn't take into account other PDF readers.

What you want is impossible. Browsers are not magic, they just display different kinds of documents, some of which (HTML) can embed objects provided by plugins (flash, java) and other documents inside iframes (pdf, flash, html). If you want to show pdf miniatures, you will have to generate images on the server.

Related

Need to set pdf viewer toolbar off

Trying to view pdf file. Toolbar is showing differently in different browsers. Is there any way to hide this toolbar in all browsers.
Code in .cshtml file:
<div id="zoomOut">
<object data="#Url.Action("ViewFinalReport", new { Id = #ViewBag.FileName, SystemId = Model.SystemId, InspectionReportId = Model.ReportId })" type="application/pdf" width="900" height="650">
</object>
</div>
Code in controller:
public FilePathResult ViewFinalReport(string Id, int SystemId, int InspectionReportId)
{
string path = "";
string filePath = "";
string customerFolderName = "";
SystemInspectionReport SystemInspectionReport = new Models.Objects.SystemInspectionReport();
TestSoln.Models.Objects.SystemInspectionReports SystemInspectionReports = new Models.Objects.SystemInspectionReports(SystemInspectionReport, new BaseParams() { customerId = CustomerId, userId = UserId, timeOffSet = TimeOffSet });
string FileName = SystemInspectionReports.GetInspectionSystemReportFileName(SystemId, InspectionReportId, true);
DataTable dataTable = GetCustomerDetails(CustomerId).Tables[0];
if (dataTable.Rows[0]["Folder"] != DBNull.Value)
{
customerFolderName = dataTable.Rows[0]["Folder"].ToString();
}
path = HttpContext.Application["FileFolder"].ToString() + "\\" + customerFolderName + "\\InspectionReports\\" + SystemId + "\\" + InspectionReportId + "\\FinalReport\\" + FileName;
filePath = new AppSettings()[AppSettingsKey.FileLocation].Value + path;
return File(filePath, "application/pdf");
}
I can view the pdf in all the browsers. But the problem is that toolbar shown differently in different browsers. So I want to hide the toolbar. Any idea??
You can use embed instead of object and just add #toolbar=0 at the end of url to remove the toolbar. Not sure if the same applies to object.
<embed src="#Url.Action("ViewFinalReport", new { ...})#toolbar=0" width="500" height="375"> (Disable toolbar)
<embed src="#Url.Action("ViewFinalReport", new { ...}#toolbar=1" width="500" height="375"> (Enable toolbar)
EDIT:
Currently there is no easy configuration that can be done and works for all browsers.
The #toolbar and some other parameter setted after # are Adobe's proprietary "PDF Open Parameters". This works on Chrome because Chrome's PDF Viewer was made with compatibility with Acrobat's parameters.
So, if your user does not use Adobe reader extension, most users uses default browser configuration, this parameters may not work. As developers we have no control on what plugin/extension the user have configured on their browser to show PDF files.
An alternative is to use Mozilla's pdf.js library, that can render the pdf file inside a canvas. At this link you will find some live examples: https://mozilla.github.io/pdf.js/examples/
This a commom problem and you can find some questions on Stack Overflow and mozilla community about it:
How can I embed a PDF in a webpage without showing the Firefox PDF viewer toolbars?
Hiding the toolbars surrounding an embedded pdf?
Can I hide the Adobe floating toolbar when showing a PDF in browser?
Hide toolbar of pdf file opened inside iframe using firefox (This one has a good explanation too)
Hiding the toolbars surrounding an embedded pdf?
https://support.mozilla.org/nl/questions/1262019
https://support.mozilla.org/en-US/questions/1119523

image not displaying in PDF template using Spring Boot, flying saucer and Thymeleaf

I create a file pdf from html template using Spring Boot, flying saucer, thymeleaf. But image is not displaying in my file.
Project structure:
code html:
<div class="col-xs-6 invoice-col-2">
<img src="../static/images/mastercard.png" alt="mastercard"></img>
</div>
When I change img tag to:
<img src="../static/images/mastercard.png" alt="mastercard" th:src="#{static/images/mastercard.png}"></img>
When I create PDF file, I get an error:
org.thymeleaf.exceptions.TemplateProcessingException: Link base "static/images/mastercard.png" cannot be context relative (/) or page relative unless you implement the org.thymeleaf.context.IWebContext interface (context is of class: org.thymeleaf.context.Context)
Try using Spring's classpath: prefix. This loads your file directly from the classpath, no matter if you are running from a .jar or within your IDE. Here is an example:
<img alt="mastercard" th:src="#{classpath:static/images/mastercard.png}" />
More information about classpath: can be found in the official documentation.
In order to embed an image in a PDF generated by Flying Saucer,
1) Convert the image to a base64 encoded string.
Path path = Paths.get("src/main/resources/static/images/mastercard.png");
String base64Image = convertToBase64(path);
Function to convert image stored in a path like shown above, to a base64 encoded string
private String convertToBase64(Path path) {
byte[] imageAsBytes = new byte[0];
try {
Resource resource = new UrlResource(path.toUri());
InputStream inputStream = resource.getInputStream();
imageAsBytes = IOUtils.toByteArray(inputStream);
} catch (IOException e) {
System.out.println("\n File read Exception");
}
return Base64.getEncoder().encodeToString(imageAsBytes);
}
2) Set the base64 encoded image in the thymeleaf context
Context context = new Context();
String image = "data:image/png;base64, " + base64Image;
context.setVariable("image", image);
String html = templateEngine.process("template", context);
3) In HTML, set the value of image as shown below:
<img th:src="${image}" style="width: 200px; height=100px"/>
4) Finally, render the HTML template to PDF
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html); // html -> String created in Step 2
renderer.layout();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
renderer.createPDF(baos)
Now you have the byteArrayOutputStream of the generated PDF, with which you can choose to store them to a file server or serve it to a client in a format of your choice.
Use standard html src atribute and relative path from root of the project.
You can put your image in the root of the project and use it like this:
<img src="mastercard.png" />
If you want to resource folders you can set it like this:
<img src="src/main/resources/static/images/mastercard.png" />
I faced the same issue but reading image file from disk is little costly, I would suggest you go with uri-data
http://www.tothenew.com/blog/using-data-urls-for-embedding-images-in-flying-saucer-generated-pdfs/
Because you anyway going to read image to generate PDF, better keep it in template.

How to disable print option for PDF in iframe

I'm showing a PDF in an <iframe> as follows:
<iframe src="/itextPdfServlet" height="600px" width="700px"></iframe>
I would like to disable the print option for this. How can I achieve this?
my servlet
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String fullPath = (String) request.getSession().getAttribute("fullPath");
response.setContentType("application/pdf");
ServletOutputStream out = null;
try{
File file = new File( fullPath );
FileInputStream fileIn = new FileInputStream( file );
out = response.getOutputStream();
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfReader reader = new PdfReader(fileIn);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("fullPath"));
stamper.setEncryption("reader_password".getBytes(), "permission_password".getBytes(),
~(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING ), PdfWriter.STANDARD_ENCRYPTION_128);
stamper.close();
PdfImportedPage page = writer.getImportedPage(reader, 1);
document.newPage();
cb.addTemplate(page, 0, 0);
document.add(new Paragraph("my timestamp"));
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
document.close();
}catch(Exception e){
}
}
Treating visitors or customers like enemies might not be in your best interest. You can disable printing in the options of a PDF file when generating the file:
PdfReader reader = new PdfReader("testpdf.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("my-pdf-file.pdf"));
stamper.setEncryption("reader_password".getBytes(), "permission_password".getBytes(), ~(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING ), PdfWriter.STANDARD_ENCRYPTION_128);
stamper.close();
But I know at least one PDF viewer which doesn't care about these options. I know a lot of tools that can make screenshots, so even if your PDF makes me angry, I just print the screenshot. There are screen automation tools that will even page through the file for me, make a screenshot for every page and a little script will compile a new PDF from that.
You can also try to disable printing with JavaScript in the web browser. That would then force me to install a tool like Tampermonkey or similar that kicks your script out of my browser.
Usually, a much better approach is to put watermarks in the PDF file which say who downloaded / bought the file and then harass them, if the PDF file leaks out. That way, you're not annoying everyone.
That said, consider how much your PDFs are worth and how much suing someone would cost (money and negative feedback wise). Most of the time, investing your money in great service will earn you much more money than you can lose by people printing PDFs (they would also have to do something with those prints before it could have any impact on your revenue, rights, ...)
I have never worked with iText, but I assume this might help you a little:
iText Java disable print pdf

printing html output to printer on a server application

I am writing a service on the local server side which will accept the printer name and other inputs from the UI application and print the html file to the desired network printer. it is not a desktop application. I have a processed html file which I am reading into a string and want its output sent to the desired printer.
1 way I could found is to create an image by reading it into a JEditorPane(though using a swing class is not great approach) and then saving an image which is then sent to the printer. But it fails when the html has an tag and that image is not renderred within the image created by html. Can someone help me with a method that can solve my problem. The printer is able to support postscripts as well.
This is my approach
protected void generateDoc(DataObj data) {
DocFlavor dsc =
DocFlavor.INPUT_STREAM.PNG;
// get the html file's contents
String receipt =
getFileContents("Receipt.html");
// process the html contents and insert the data details
receipt = processHTMLContents(receipt, data);
// create image of the receipt
createReceiptImage(receipt);
InputStream is =
null;
try {
is =
new FileInputStream(new File("testingToday.png")); // the same image which was created below
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// create the doc to be sent to the printer
Doc doc =
new SimpleDoc(is, dsc, null);
return doc;
}
/**
* Create an image of the html receipt.
* #param htmlReceipt processed html receipt
* #return
* #throws InterruptedException
*/
protected void createReceiptImage(String htmlReceipt) throws InterruptedException {
JEditorPane pane =
new JEditorPane();
//pane.setEditable(false);
pane.setEditorKit(new HTMLEditorKit());
pane.setContentType("text/html");
pane.setText(htmlReceipt);
pane.setSize(650, 850);
pane.setBackground(Color.white);
// Create a BufferedImage
BufferedImage image =
new BufferedImage(pane.getWidth(), pane.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g =
image.createGraphics();
// Have the image painted by SwingUtilities
JPanel container =
new JPanel();
SwingUtilities.paintComponent(g, pane, container, 0, 0, image
.getWidth(), image.getHeight());
g.dispose();
ImageIO.write(image, "PNG", new File("testingToday.png")); // this would be replaced by a relative network location
}
and this doc is then sent to the printer. but this is not a desirable approach as it is swing class and it is not able to render any images inside the html. I have already spent around a week over it but still cant end upon a solution. how to fix this or what can be the solution?
Although the question seems old, you can have a look at this question.. Basically it converts a HTML to PDF & then you print the PDF... hope this helps

Html Image src path with shared network is not working in firefox

In My webpage i am using a image tag, the src attribute is pointing to shared network location ie (/server/images/image1.png). The exact script is "<img src="file://///server/images/image1.png". It is working fine in IE. In firefox, when I do debug using firebug its showing image, but it's not displayed in page (user view). Even it's working fine when copy this location and place it in firefox address bar. What will be the problem while using img tag also what is the solution for this? Thanks in advance.
Putting this as an answer here so as to provide help for others like myself that was searching for how to display networked images and came accross this SO post in the top 3 search engine results. It also seems like a better answer than the java servlet issuing images in the response.
FireFox would not display networked images so I created an MVC helper that extends HtmlHelper.
public static class ImageHelper
{
/// <summary>Converts a photo to a base64 string.</summary>
/// <param name="html">The extended HtmlHelper.</param>
/// <param name="fileNameandPath">File path and name.</param>
/// <returns>Returns a base64 string.</returns>
public static MvcHtmlString PhotoBase64ImgSrc(this HtmlHelper html, string fileNameandPath)
{
var byteArray = File.ReadAllBytes(fileNameandPath);
var base64 = Convert.ToBase64String(byteArray);
return MvcHtmlString.Create(String.Format("data:image/gif;base64,{0}", base64));
}
}
use in the MVC View like so:
using
<img src="#Html.PhotoBase64ImgSrc(image)" height="60px" width="60px" alt="photo" />
here the 'image' in #Html.PhotoBase64ImgSrc(image) is a pure network UNC, e.g.
//Photos/ebaebbed-92df-4867-afe8-0474ef8644eb.jpg
Create a regular HTML img element like so:
<img id="image1" runat="server" ImageUrl=<%# Eval("Value") %>/>
And in code behind do this:
image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes);
Where bytes is a byte[].
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["FileName"] != null)
{
// Read the file and convert it to Byte Array
string filePath = "C:\\Users\\Public\\Pictures\\Sample Pictures\\";
string filename = Request.QueryString["FileName"];
string contenttype = "image/" + Path.GetExtension(filename).Replace(".", "");
FileStream fs = new FileStream(filePath + filename, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes);
}
}
You are done. The image will be displayed.
The solution usually is: use a web server.
You may have to make it like so.
<img src="../server/images/image1.png" />
Once you add the "../" it is basically telling your browser to go back one directory to search for the location after the "../" .
Where is the file located and where is the location of your HTML document?
UPDATE:
I do all of my work on a Network Server as well... This should do the trick.
<img alt="" src="file:///SERVER:/FOLDER/IMAGES/image1.png" />
Thanks,
Aaron
I wrote a servlet which reads the file from LAN using Java File Stream and sets it in response and it does the trick. Thanks to all for valuable response.