Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

javascript - Print PDF Created using itextsharp

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...