Generate PDF with itextsharp Library

I am looking to generate an RDLC report on the client's machine without having to preview it. Since I cannot use the ReportViewer print button due to restrictions with ActiveX installation, I have opted to utilize ITextSharp to convert the rendered LocalReport into a PDF and incorporate JavaScript for printing.

While debugging, I can confirm that the PDF is successfully created with 2 pages and everything appears to be in order. However, despite no errors being reported and the function exiting properly, the document does not print. I'm unsure of what I might be overlooking or doing incorrectly.

Below is the snippet of my code:

string jsPrint = "var pp = this.getPrintParams();pp.interactive= pp.constants.interactionLevel.silent;this.print(pp);";

byte[] bytes = report.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);

using (MemoryStream ms = new MemoryStream())
{
    Document doc = new Document();

    PdfWriter writer = PdfWriter.GetInstance(doc, ms);

    doc.SetPageSize(PageSize.A4);

    doc.Open();

    PdfContentByte cb = writer.DirectContent;

    PdfImportedPage page;

    PdfReader reader = new PdfReader(bytes);

    int pages = reader.NumberOfPages;

    for (int i = 1; i <= pages; i++)
    {
        doc.SetPageSize(PageSize.A4);

        doc.NewPage();

        page = writer.GetImportedPage(reader, i);

        cb.AddTemplate(page, 0, 0);
    }

    PdfAction jAction = PdfAction.JavaScript(jsPrint, writer);

    writer.AddJavaScript(jAction);

    doc.Close();
}

Any insights would be greatly appreciated. Thank you.

Answer №1

Concerning your inquiry regarding the utilization of PdfStamper (as mentioned in the comments), here is a straightforward approach:

string jsPrint = "var pp = this.getPrintParams();pp.interactive= pp.constants.interactionLevel.silent;this.print(pp);";
PdfReader reader = new PdfReader(bytes);
MemoryStream stream = new MemoryStream();
PdfStamper stamper = new PdfStamper(pdfReader, stream);
stamper.Writer.AddJavaScript(jsPrint);
stamper.Close();
reader.Close();

In relation to your initial question: the automatic printing of PDF files is viewed as a security risk due to the potential for unauthorized pages being printed by sending a malicious PDF document. This was feasible with outdated PDF viewers, but modern viewers have safeguards in place to prevent such actions.

To clarify: it appears you may be attempting to fulfill an outdated requirement. Present-day PDF viewers typically require user interaction to print a document.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating multiple unique custom attributes for a specialized HTML element

Creating getter/setter methods for a custom attribute on a custom HTML element is quite simple: customElements.define('custom-el', class extends HTMLElement { static get observedAttributes() { return ['customAttr'] ...

Methods for transferring the true/false state of a semantic checkbox to e.target

In order to pass the values of state.TNC and state.promos into the emailjs.sendForm, the submitted email should display 'true' if the box is checked, and 'false' if not. I am struggling to find a solution that involves semantics and em ...

Why does my camera suddenly switch to a rear-facing view when I begin my Zoom meeting?

I am facing an issue with my camera function where it initially starts off facing backwards, but as soon as I perform the first scroll, it flips around and works correctly. Please note that I am a beginner in coding. Kindly be aware that there is addition ...

Enhancing dynamic checkboxes with mouseover functionality

Can someone help me figure out how to implement a mouseover effect for checkboxes? I want the checkbox to display more information about the subject when someone hovers over it. Here is the code I have for generating dynamic checkboxes, but I'm not s ...

Deciphering Windows Authentication in ASP.NET MVC 4: A Guide to Understanding and Testing the Process

Although I have always used Forms Authentication for ASP.NET MVC web applications in the past, I now find myself needing to implement Windows Authentication for a new ASP.NET MVC 4 web application on my company's web server. This has led me to some qu ...

Showing information using ng-repeat from a JSON collection

Here is the JSON data I am working with: $scope.track = [{ title: 'Group Therapy 150 with Above & Beyond and Maor Levi', date: new Date(), link: "https://www.mixcloud.com/widget/iframe/?embed_type=widget_standard& ...

Are the orders of events maintained when emitted using an event emitter?

I have a simple query regarding the event emitter, which is crucial for my program's logic. Currently, I am utilizing an external library that triggers events that I'm listening to. These events consist of 'data' and 'error'. ...

Error in Google PHP and MySQL integration with Google Maps demonstration using Javascript

I've been working on implementing the Google Maps API Family example called "Using PHP/MySQL with Google Maps" (Example): Initially, I thought it would be a straightforward process with some interesting discussions. However, surprisingly, most of it ...

JS Function created to supply elements to React component is failing to return correctly

Trying to validate a dataset by checking for specific prefixes or suffixes in a string, and then breaking the string into <span> elements. The current function correctly identifies the relevant morphemes in the data set, but fails to return the split ...

Issue encountered in the express route when attempting to send an email to the user with nodemailer and reactjs

When attempting to send an email to the user who submitted the application using ReactJS and Nodemailer, an error stating "route not found" is encountered. Warning: Location "/contact?name=milan&email=xedikaka%40gmail.com&phone=9843698469&city ...

Ending or stopping based on data retrieved from an ajax call

Currently, I have a php script that includes an image which, upon clicking, redirects the user to a different page. Additionally, there is an ajax/jQuery function in place to check if the user is logged in or not. When the user clicks on the link, the aja ...

Why aren't the validations being set when creating Angular forms using formControl.values?

I had to structure the form in a specific way in my app.ts file -> courseNameControl = new FormControl("", [Validators.required,Validators.minLength(2)]); contentControl = new FormControl("", Validators.required); form = { cours ...

Exploring the realm of variable scope in JavaScript and Vue.JS

I am a newcomer to JavaScript and I have encountered an issue with the scope of my object/variable. Can you please help me understand why my {endtoken:this.token} is empty, while console.log({rawToken:e.data}) is not? I find the concept of variable scope ...

Creating a nested object in React's handleChange method: a step-by-step guide

Hey there, I've been working on an onChange function called handleChange for a set of dynamically created inputs. This function receives the event and then performs the following actions: const handleChange = (e) => { const updatedValues = [...va ...

Sending information to Firebase using Angular 4

Utilizing Angular 4 in combination with AngularFire, I have successfully implemented a data transfer to Firebase. The specific data that I am looking to retrieve includes: name, country, zip-code paired with email and password details. Following the upda ...

Eliminate repetitive elements from an array using a specific merging algorithm

Here's a thought I have: If we have an array of objects like this: [ { "name": "Kirk", "count": 1 }, { "name": "Spock", "count": 1 }, { "name": "Kirk", "count": 1 } ] I would l ...

Sorry, but React does not accept objects as valid children. Make sure the content you are passing is a valid React child element

I encountered an issue with rendering on a screen that involves receiving an object. The error message I received is as follows: Error: Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X}). If you meant to render a collection o ...

retrieve the value of the 'show' variable before displaying it

Trying to figure out the logic behind a question but coming up empty. In my JavaScript app using OOP, I'm attempting to assign a function as a variable value. Initially, the value of init_s.__temp_var is an empty object. When the function logic_s.get ...

Stopping the carousel animation in Bootstrap 5: A step-by-step guide

I'm struggling to stop a Bootstrap 5 carousel with a button click. The pause function seems to be ineffective. You can view the code on Code Pen Example or see the code below. document.getElementById("btnPause").addEventListener("clic ...

SignalR is exclusively accessible within the active SILO environment

Currently, I am working on a real-time application using SignalR in combination with MVC and AngularJS (SILO). Each cshtml page serves as a Single Page Application (SPA), and within my AngularJS common service, I have incorporated generic operations such a ...