Print PDF Created using itextsharp

2019-01-27 07:06发布

My Goal is to print a RDLC report on the client machine without preview. I can not use the ReportViewer print button since it requires the installation of ActiveX object and there are no permissions for that. So, I'm using ITextSharp to create a PDF from the byte array returned from the rendered LocalReport, and add a JavaScript for print.

During Debug, I can see that the PDF is generated and has 2 pages, and everything looks OK. I don't receive any errors and the function exits OK, but it doesn't print. What am I doing wrong, or what am I missing?

This is 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();
}

Thanks.

1条回答
\"骚年 ilove
2楼-- · 2019-01-27 07:23

Regarding your question about PdfStamper (in the comments). It should be as simple as this:

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();

Regarding your original question: automatic printing of PDF documents is considered being a security hazard: one could send a PDF to an end-user and that PDF would cause the printer to spew out pages. That used to be possible with (really) old PDF viewers, but modern viewers prevent this from happening.

In other words: you may be trying to meet a requirement of the past. Today's PDF viewers always require an action from the end user to print a PDF document.

查看更多
登录 后发表回答