iTextSharp | Failing to Output PDF in IE - c#

I recently encountered an issue regarding outputting a PDF generated in iTextSharp into a new window and haven't been able to figure out a way to fix the issue.
This problem only seems to occur in IE, and upon the new window opening, it remains blank and doesn't seem to load the PDF at all. (Where as Chrome and Firefox seem to work just fine)
I'll go through an overview of the process in hopes of providing some assistance to you all:
Step 1:
The User clicks the "Print" button that I have within a View, and this calls the following Javascript to execute:
window.open($("#PrintURL").val(), 'Print_Preview', 'resizable=1');
Step 2:
The URL that is called pulls the appropriate data into a model and then passes that into a partial view, which is passed into a PDFResult, as shown:
//Grabs the Data
var data = reportAgent.GetData();
//Builds a string that contains the Report layout and builds the Report
string html = ControllerContext.RenderPartialAsString("~/Views/Reports/Report.cshtml", data);
return new PDFResult(html, ...);
Step 3:
Within the PDFResult ExecuteResult() method, I build the document that the Report will output, and adjust other parameters, such as PageSize, Headers and Footers.
public override void ExecuteResult(ControllerContext context)
{
//Sets Response to output a PDF
var response = context.HttpContext.Response;
response.ContentType = "application/pdf";
//Generate Document
Document document = new Document();
//Sets Page Size and Styles
//Build Headers and Footers and Add to Document
//Builds the document writer and prepares a Print Dialog upon opening
PdfWriter writer = PdfWriter.GetInstance(document, context.HttpContext.Response.OutputStream);
PdfAction action = new PdfAction(PdfAction.PRINTDIALOG);
writer.SetOpenAction(action);
writer.PageEvent = page;
document.Open();
//Iterates through the html string that was passed in and formats the document
document.Close();
}
I cannot seem to figure out why the new window simply remains blank in Internet Explorer, while a majority of other browsers seem to work just fine. (I know I have had this same process work in IE in the past, I'm just stumped currently.)
Any idea/suggestions to improve this process would be greatly appreciated.
UPDATE
I was testing out some of the changes suggested, and when I removed the areas that would build the document and just added the following:
document.Add(new Phrase("TEST"));
which would add just a single line to the PDF and then generate it. I received an "Internet Explorer cannot display the webpage" error, with the option to Diagnose Connection Problems. When clicking the Diagnose Connection Problems option, and it finishes, the PDF is loaded as intended.
Could this be an issue with the PDF not being "ready" when the new window attempts to load it?
(This is in IE8)

I managed to finally solve this issue. It appears that the window was opening prior to the PDF being ready to be displayed. (This was determined by simply refreshing the window and then the PDF would appear properly.)
So rather than opening the window to a specific URL, I generated a window and opened the URL from within the window, which seemed to fix the issue.)

Related

PDFSharp blank pages

Tried to open a pdf result in blank pages. Retry with same pdf displayed all pages with content.
It happen only once & couldn't reproduce it.
My application work with 3 steps.
Open PDF
Add Barcode Image
Save PDF
Source pdf had 2 pages with text content, output pdf had only stamped pdf without content.
I believe something went wrong in following line because number of pages are correct but blank.
PdfDocument document = PdfReader.Open(filePath, PdfDocumentOpenMode.Modify);
I need find reason of failure but don't have any idea what went wrong at first time. I have already gone through following questions but they have different case.
https://stackoverflow.com/a/52453789/9102192
PDFSharp returning blank pages when adding password
Can anyone help me finding root cause for this incident or any guesses ?
I would try to do something like this:
using (PdfDocument pdfDoc = PdfReader.Open("source", PdfDocumentOpenMode.Modify)){
// Logic to insert image into pdf //
pdfDoc.Save("targetPath")
}

How to Embed iTextSharp PDF in View (C# - MVC 5)

Greetings fellow coders!
I've done tons of research on this topic and can't manage to find any resources that truly depict how this process can be done (or if it can be done). So, I'm turning to you all for some advice!
The Issue:
So right now, I have a form that sends the filled out data back to the controller via HttpPost. At this point, I pass that form data to the model function to create the PDF. Now at this point, I have it returning the PDF file if the model function was successful.
PDFMemStream memstream = new PDFMemStream();
CreatePDFinfo formdata = new CreatePDFinfo();
if (ModelState.IsValid)
{
memstream = CreatePDF.Populate_PDFcontent(formdata);
if (memstream.retval.success)
{
// if creating pdf is successful, return file
return File(memstream.mstream, "application/pdf");
}
}
ViewBag.PageTitle = "Cool PDF Project";
ViewBag.TabTitle = "Really Cool PDF Project";
return View(formdata);
I can display this created PDF in a separate tab if I use the code below in the view. This assumes that the current view is called "createPDF". So this part works all fine and dandy.
$('#form').submit(function () {
if ($('#form').valid())
{
window.open('', 'createPDF');
this.target = 'createPDF';
}
});
If I don't use the above code, after the button click, it will remain on the current page and reload the page with only the pdf content in the native browser PDF viewer.
The Needed Solution:
As I stated, everything works perfectly if I wanted the PDF to be populated in at new tab or the existing one. HOWEVER, what I need, is a way to view the PDF on the same page either in a partial view or embedded on the existing page. I could even deal with the PDF being embedded in a new view as long as I could pass the model data to the new view for other sections of that page.
Resources & Articles:
Here's all of the articles and resources I've already looked into and read (so please do not post the same ones):
using ITextSharp to extract and update links in an existing PDF
Displaying a pdf to webpage using iTextSharp?
http://developers.itextpdf.com/content/itext-7-jump-start-tutorial/sharp/chapter-1-introducing-basic-building-blocks
MVC Application to Display embedded PDF documents
https://www.codeproject.com/Questions/890372/How-Can-I-Display-A-Pdf-From-Byte-Array-In-Mvc
https://www.codeproject.com/Articles/66948/Rendering-PDF-views-in-ASP-MVC-using-iTextSharp
C# ASP.NET MVC Create PDF from view Rotativa or iTextSharp?
Convert PartialView Html to String for ITextSharp HtmlParser
How to open a PDF file in an <iframe>?
How to render an ASP.NET MVC View in PDF format
Now some of the articles aren't completely relevant but I included them just in case they may be helpful.
UPDATE:
In case anyone else runs into a similar issue, what I ended up doing was processing the non-PDF related method first, returned a new view with the model data, and then made an AJAX call to a route that creates/generates the PDF. Hopefully that makes sense. Haha. :)
Any suggestions, tips or advice?...

image created by httphandler is not shown in google chrome but it works only in IE

I am using Asp.Net ChartControl for Visualization. This control creates in memory image & that image is rendered as response from server to client.
Example path of image.
http://WebsiteName/ChartImg.axd?i=chart_d9a62d4ec93b4b479337b2a204957c75_1.png&g=4e7c77bc2c374858a9b8b387acabf650
This works fine in IE but it does not work in Chrome or FireFox.
Let me know if you need any details about my problem.
Edit
Merging comments
I created a user control
ChartEmbedControl embedControl = page.LoadControl("~/UserControls/ChartEmbedControl.ascx") as ChartEmbedControl;
Then i bind all required data to it & then converted it into html string like:
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter writer = new HtmlTextWriter(sw);
embedControl.RenderControl(writer);
// and then...
page.Response.Write(sb.ToString());
This is the response of one ajax call made from javascript. Response contains Image with given path(Path is mentioned in problem statement). Image is shown in IE but not in chrome
In Chrome, press F12, and see if there are any errors under 'console'. Or maybe other hints to what is wrong (from access denied to not found)
If you want, post a public URL, I can look for you.

how to hide save and print button when pdf is opened in browser using asp.net c#?

i have a problem that i can restrict user to download pdf,i only view the pdf document to user
in a browser my code is below:
string filepath = Server.MapPath(dt.Rows[0]["FilePath"].ToString());
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(filepath);
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "inline;filename=data.pdf#toolbar=0&navpanes=0");
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
but the above code can't hide the toolbar in browser..please help
What you ask cannot be achieved on every browser with every PDF reader plugin. You do not have control over which PDF reader your users may use, for example.
If the user can view the PDF, they can download it. There is nothing you can do to prevent this. The only way to prevent them from saving it locally is not to let them view it in the first place.
And even if you were able to prevent the system from allowing the file to be saved, you cannot protect against the analog hole. The user could simply take a photo of his monitor, for example, or retype the contents into a new document.
If the user can view it, then they can print it.
Hiding the Save or Print button does not secure the PDF file, if you need protection in PDF, consider securing the PDF.
Abobe.com : PDF File Protection

How to add image background to pdf for every page?

I'm trying to set a background to a pdf and managed to set it with an image my pdf has a big table so the pages are added automatically not with the Document.NewPage() method so the image background is set only on the first page. This is the code that adds the background:
Image backImg = Image.GetInstance(#"D:\websites\DIS\bugs\130208\A4.png");
backImg.SetAbsolutePosition(0, 0);
backImg.Alignment = Image.UNDERLYING;
var doc = new Document(pageSize);
PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
doc.Open();
doc.Add(backImg);
...
creating a big table
and not using the doc.NewPage() method. Do I have to loop throw every page and add the background image at the end before closing the doc, but how do I put it in the background not on top of the other elements?
Whenever you want to apply something to every page, you should use page events, more specifically PdfPageEvent.onEndPage(), to do it. You can find samples for its usage by keyword Page events > onEndPage --- these samples are taken from iText in Action 2nd Edition. The samples mainly add footers and headers while you want to add background graphics.
Be aware that you shouldn't add content to the Document instance here but instead directly to the PdfWriter, and as you want the image to be under the page content , not above it, you will need to use PdfWriter.getDirectContentUnder() like in the sample Stationery and not PdfWriter.getDirectContent() like in the other samples.
PS: The analogous samples for .Net can be found here.
PPS: The sample ImageDirect.java / ImageDirect.cs shows how to add an image to some direct content which might be the information missing here.
go for
PdfPageEvent.onStartPage()
. In this event, write your code to insert the image (as you are doing it). What it will do is that as soon as a new page is created, it will add the image to it and then the content over it; giving a watermark effect.

Categories

Resources