Primefaces generate pdf and display on click of button - pdf

I have a requirement in which I have to generate a pdf and then on click of button "SHOW PDF", I have to display on another window.
I have been able to generate a pdf using IText and stored in my machine. I get a java.io.File object as my return value from my backend library which needs to be displayed on the screen. Can someone please guide me how to do this?
My xhtml file has the following code snippet:
<h:commandLink action="PdfDisplayRedirect.xhtml" target="_blank">show PDF</h:commandLink>
my PdfDisplayRedirect.xhtml has the following code:
<p:media value="#{pdfGenerationAction.fileName}" width="100%" height="300px">
Your browser can't display pdf, <h:outputLink value="InitialExamination33.pdf">click</h:outputLink> to download pdf instead.
My backing bean has the following code:
private File initialExaminationFile;
private generateFile(){
this.initialExaminationFile = backendService.generateFile();
}
On clicking, I get a new window opened but the pdf file is not displayed.. Instead my screen from where I had invoked the command gets displayed there.
Any help would be really appreciated.
Thanks

Thanks for the response and no response.
I have found a solution myself which I would like to post so that those looking for a solution can use it.
My xhtml file included a commandlink
<p:commandLink actionListener="#{pdfGenerationAction.generatePDF(initialExaminationEMRAction.patientID)}" oncomplete="window.open('PdfDisplayRedirect.xhtml')">broadcast Msg</p:commandLink>
My pdfGenerationAction bean file had the following lines of code:
FileInputStream fis = new FileInputStream(this.initialExaminationFile);
//System.out.println(file.exists() + "!!");
//InputStream in = resource.openStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum); //no doubt here is 0
//Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
System.out.println("read " + readNum + " bytes,");
}
this.reportBytes = buf;
}
I converted my file into bytearraystream and made it available in my session. Then I followed the suggestion given by BalusC at Unable to show PDF in p:media generated from streamed content in Primefaces

Related

how can I show the pdf file content inside from razor file

I created a document file from word and has exported as pdf . i want to show the pdf content inside the Div element in razor page. How can I show the pdf content from razor page. Please can you provide an example code how to show in blazor server side
If you stored your pdf file directly in your documents for example in the folder wwwroot/pdf.
wwwroot/pdf/test.pdf
You can display this PDF with this line of html bellow :
< embed src="pdf/test.pdf" style="width=100%; height=2100px;" />
It will provide you a pdf displayer with printing options !
If you want to go further, upload your file and then display it, I will recommend you to go check this explanation :
https://www.learmoreseekmore.com/2020/10/blazor-webassembly-fileupload.html
The upload for PDF files works the same as Img file, you need to go check IBrowserFile documentation.
You will see that it has a Size obj and a OpenReadStream() function that will help you get the display Url for your file (image or pdf)
If the site abow closes, this is the upload code that is shown on it :
#code{
List<string> imgUrls = new List<string>();
private async Task OnFileSelection(InputFileChangeEventArgs e)
{
foreach (IBrowserFile imgFile in e.GetMultipleFiles(5))
{
var buffers = new byte[imgFile.Size];
await imgFile.OpenReadStream().ReadAsync(buffers);
string imageType = imgFile.ContentType;
string imgUrl = $"data:{imageType};base64,{Convert.ToBase64String(buffers)}";
imgUrls.Add(imgUrl);
}
}
}
This code was written by Naveen Bommidi, author of the blog where I found this usefull code
If you want, as I said, upload a PDF and then display it.
You can use the same html line :
< embed src="#imgUrl" style="width=100%; height=2100px;" />
And your uploaded files will be displaying.
Example

Report screenshot attachment link is confused

I've embedding several screenshots of various states of UI. The screenshots are attached however, the link to view the attachments are confused and opening another attachment on the report.
For e.g. 'Attachment 1 (PNG)' link to a screenshot opens/collapses the 2nd screenshot and the same with others.
I'm wondering if there is an option to customize a link text, instead of saying "Attachment 1 (PNG)" to something like "Current User Data Screenshot", to be more interactive.
I tried to upgrade the cucumber-JVM version but the issue is still there.
You can rename the screenshot file and then attach to the scenario.
//take screenshot using selenium
File src = driv.getScreenshotAs(OutputType.FILE);
//Rename the file
File newfile =new File("Current User Data Screenshot"); // Need absolute file name
if(src.renameTo(newfile)){
System.out.println("File renamed");
}else{
System.out.println("Sorry! the file can't be renamed");
}
//convert the screenshot to byte array
BufferedImage o=ImageIO.read(newfile);
ByteArrayOutputStream b=new ByteArrayOutputStream();
ImageIO.write(o, "png", b);
byte[] myscreenshot=b.toByteArray()
//Attach the screenshot to scenario
scenario.embed(myscreenshot,"image/png");

Print PDF in Website

I have been searching for days for a solution to this problem.
Description : I have a website which loads a PDF dynamically via an iFrame. The PDF is saved on the server and the user of the website can view the pdf on the website.
Problem : Introduce a Print button on website which prints the PDF which was created dynamically and saved on the server.
Is this even possible ? I am looking at a cross-browser implementation as well to make things worse. I have tried n number of JS options from the web but none of them seem to work. I can not seem to get the PDF printed in the same way as it looks. To put it short, I am trying to emulate the print button which appears on the PDF when it is loaded. Is there an option to pass the pdf document from the server to the print dialog box ?
Description : I have a website which loads a PDF dynamically via an iFrame. The PDF is saved on the server and the user of the website can view the pdf on the website.
Problem : Introduce a Print button on website which prints the PDF which was created dynamically and saved on the server.
Solution : I could not find an exact solution to this problem, but here is how I solved the problem -
Create the 'Print' as per req and redirect that to another page which has only the PDF.
Copy the previous PDF & Create new PDF with JS - this.print() such that when it opens up, the print dialog pops up directly to the user.
In the new page -
if ("Location of PDF " != null)
{
sPdf = "Location of PDF ";
PdfReader pReader = new PdfReader(sPdf);
Document document = new Document
(pReader.GetPageSizeWithRotation(ApplicationConstants.INDEX_ONE));
int n = pReader.NumberOfPages;
FileStream fs = new FileStream
("New PDF location",
FileMode.Create, FileAccess.Write);
PdfCopy copy = new PdfCopy(document, fs);
// Write to pdf
document.Open();
for (int i = ApplicationConstants.INDEX_ONE; i <= n; i++)
{
PdfImportedPage page = copy.GetImportedPage(pReader, i);
copy.AddPage(page);
}
copy.AddJavaScript("this.print(true);", true);
document.Close();
pReader.Close();
inStr = File.OpenRead("New PDF location");
while ((bytecnt = inStr.Read
(buffer, ApplicationConstants.INDEX_ZERO, buffer.Length))
> ApplicationConstants.INDEX_ZERO)
{
if (Context.Response.IsClientConnected)
{
Context.Response.ContentType = "application/PDF";
Context.Response.OutputStream.Write(buffer,
ApplicationConstants.INDEX_ZERO, buffer.Length);
Context.Response.Flush();
}
}
}
Please note that I am using itextsharp to inject the JS script into the new PDF. Hope this helps someone else. I am trying to find another solution without the usage of itextsharp or any other dll but this will have to do for now.
I am not sure if this will work, but you could try launching a popup window with a special version of your PDF file that opens the print dialog when opened. Then close the popup afterwards. This last part might be tricky since I think there is no clean way to know if the print dialog has been closed.

Print one page of WebBrowser

I am trying to automate printing of intranet websites. Since this is an application that will be put on a specific user's computer, which will be run on an as-needed basis, I'd like it to be as un-disruptive as possible (in other words, not launching IE for each page). The catch is that I need to print the first page of the website and then print the whole website again, which will produce the first page two times. What is the best way to do this?
I have no problem getting it to loop through the pages that it needs to print, nor do I have a problem opening the page with webbrowser. I do, however, have a problem specifying a print range.
I also tried PrintDocument, but couldn't figure out how to get that to open within the form.
Thanks for any help that can be provided.
To download the pdf file, try this solution using iTextSharp:
ITextSharp HTML to PDF?
Except with one substitution if you want to save directly to a file
private MemoryStream createPDF(string html)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(html);
// step 1: creation of a document-object
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
// step 2:
// we create a writer that listens to the document
// and directs a XML-stream to a file
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c:\\my.pdf", FileMode.Create));
// step 3: we create a worker parse the document
HTMLWorker worker = new HTMLWorker(document);
// step 4: we open document and start the worker on the document
document.Open();
worker.StartDocument();
// step 5: parse the html into the document
worker.Parse(reader);
// step 6: close the document and the worker
worker.EndDocument();
worker.Close();
document.Close();
return msOutput;
}
Once the PDF is set up, try ghostscript to print one page:
Print existing PDF (or other files) in C#
If you start a shell execute of the process, you can use the command line arguments:
gsprint "filename.pdf" -from 1 - to 1
Alternatively, WebBrowser can just print the full page: http://msdn.microsoft.com/en-us/library/b0wes9a3.aspx
I can't find anything referencing that WebBrowser itself can print "From page X to Y" without a print dialog.
Since I'm facing a similar problem, here's an alternate solution:
This open source project turns HTML documents to PDF documents similar to iTextSharp (http://code.google.com/p/wkhtmltopdf/). We ended up not using iTextSharp because of several formatting issues with the way the site we wanted to print was laid out. We send command line arguments to turn the html downloaded using a webclient into a pdf file.
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultNetworkCredentials;
string htmlText = wc.DownloadString("http://websitehere.com);
Then, after turning to pdf, you can simply print the file:
Process p = new Process();
p.StartInfo.FileName = string.Format("{0}.pdf", fileLocation);
p.StartInfo.Verb = "Print";
p.Start();
p.WaitForExit();
(Apologies for C#, I'm more familiar with it than VB.NET, though it should be a simple conversion)

how to display a pdf document in jsf page in iFrame

Can anyone help me in displaying PDF document in JSF page in iframe only?
Thanks in advance,
Suresh
Just use <iframe> the usual way:
<iframe src="/path/to/file.pdf"></iframe>
If your problem is rather that the PDF is not located in the WebContent, but rather located somewhere else in disk file system or even in a database, then you basically need a Servlet which gets an InputStream of it and writes it to the OutputStream of the response:
response.reset();
response.setContentType("application/pdf");
response.setContentLength(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 {
close(output);
close(input);
}
This way you can just point to this servlet instead :) E.g.:
<iframe src="/path/to/servlet/file.pdf"></iframe>
You can find a complete example of a similar servlet in this article.
The <iframe> also works fine in JSF, assuming that you're using JSF 1.2 or newer. In JSF 1.1 or older you have to wrap plain vanilla HTML elements such as <iframe> inside a <f:verbatim> so that they will be taken into the JSF component tree, otherwise they will be dislocated in the output:
<f:verbatim><iframe src="/path/to/servlet/file.pdf"></iframe></f:verbatim>
I recommend you to have a look at http://www.jpedal.org/. You can convert each of the pdf pages to images and deliver them separately to the browser.
This approach is more secure for your application, since the pdf is never send to the client.