简体   繁体   English

Aspx到PDF iTextSharp的用法

[英]Aspx to PDF iTextSharp usage

I have this code which I merged and modified for my needs. 我有此代码,可以根据自己的需要进行合并和修改。 But I still can't make it work as I need. 但是我仍然无法使其按需运行。 The first part that I made, it generates PDF with an option from aspx page chosen. 我制作的第一部分,它会生成PDF,并从apx页面中选择一个选项。 Second, I need to have the background over the page, so I added next code, but now it generates just the second code and not the PDF. 其次,我需要页面的背景,所以我添加了下一个代码,但是现在它仅生成第二个代码,而不是PDF。 And im not able to merge those codes together. 而且我无法将这些代码合并在一起。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

public partial class CreatePDFFromScratch : System.Web.UI.Page
{
    protected void btnCreatePDF_Click(object sender, EventArgs e)
    {
        // Create a Document object
          var document = new Document(iTextSharp.text.PageSize.LETTER.Rotate(), 0f, 0f, 0f, 0f);

        // Create a new PdfWrite object, writing the output to a MemoryStream
        var output = new MemoryStream();
        var writer = PdfWriter.GetInstance(document, output);

        // Open the Document for writing
        document.Open();

        // First, create our fonts..
        var titleFont = FontFactory.GetFont("Arial", 18, Font.BOLD);
        var subTitleFont = FontFactory.GetFont("Arial", 14, Font.BOLD);
        var boldTableFont = FontFactory.GetFont("Arial", 12, Font.BOLD);
        var endingMessageFont = FontFactory.GetFont("Arial", 10, Font.ITALIC);
        var bodyFont = FontFactory.GetFont("Arial", 12, Font.NORMAL);

        // Add the "Northwind Traders Receipt" title
        document.Add(new Paragraph("Northwind Traders Receipt", titleFont));

        // Now add the "Thank you for shopping at Northwind Traders. Your order details are below." message
        document.Add(new Paragraph("Thank you for shopping at Northwind Traders. Your order details are below.", bodyFont));
        document.Add(Chunk.NEWLINE);

        // Add the "Order Information" subtitle
        document.Add(new Paragraph("Order Information", subTitleFont));

        // Create the Order Information table 
        var orderInfoTable = new PdfPTable(2);
        orderInfoTable.HorizontalAlignment = 0;
        orderInfoTable.SpacingBefore = 10;
        orderInfoTable.SpacingAfter = 10;
        orderInfoTable.DefaultCell.Border = 0;

        orderInfoTable.SetWidths(new int[] { 1, 4 });
        orderInfoTable.AddCell(new Phrase("Order:", boldTableFont));
        orderInfoTable.AddCell(txtOrderID.Text);
        orderInfoTable.AddCell(new Phrase("Price:", boldTableFont));
        orderInfoTable.AddCell(Convert.ToDecimal(txtTotalPrice.Text).ToString("c"));

        document.Add(orderInfoTable);

        // Add the "Items In Your Order" subtitle
        document.Add(new Paragraph("Items In Your Order", subTitleFont));

        // Create the Order Details table
        var orderDetailsTable = new PdfPTable(3);
        orderDetailsTable.HorizontalAlignment = 0;
        orderDetailsTable.SpacingBefore = 10;
        orderDetailsTable.SpacingAfter = 35;
        orderDetailsTable.DefaultCell.Border = 0;

        orderDetailsTable.AddCell(new Phrase("Item #:", boldTableFont));
        orderDetailsTable.AddCell(new Phrase("Item Name:", boldTableFont));
        orderDetailsTable.AddCell(new Phrase("Qty:", boldTableFont));

        foreach (System.Web.UI.WebControls.ListItem item in cblItemsPurchased.Items)
            if (item.Selected)
            {
                // Each CheckBoxList item has a value of ITEMNAME|ITEM#|QTY, so we split on | and pull these values out...
                var pieces = item.Value.Split("|".ToCharArray());
                orderDetailsTable.AddCell(pieces[1]);
                orderDetailsTable.AddCell(pieces[0]);
                orderDetailsTable.AddCell(pieces[2]);
            }

        document.Add(orderDetailsTable);


        // Add ending message
        var endingMessage = new Paragraph("Thank you for your business! If you have any questions about your order, please contact us at 800-555-NORTH.", endingMessageFont);
        endingMessage.SetAlignment("Center");
        document.Add(endingMessage);

        document.Close();

        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", string.Format("inline;filename=Receipt-{0}.pdf", txtOrderID.Text));

        ///create background

        Response.BinaryWrite(output.ToArray());

        Response.Cache.SetCacheability(HttpCacheability.NoCache);

    string imageFilePath = Server.MapPath(".") + "/images/1.jpg";

    iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);

    Document pdfDoc = new Document(iTextSharp.text.PageSize.LETTER.Rotate(), 0, 0, 0, 0);

    jpg.ScaleToFit(790, 777);

    jpg.Alignment = iTextSharp.text.Image.UNDERLYING;

    pdfDoc.Open();

    pdfDoc.NewPage();       

    pdfDoc.Add(jpg);

    pdfDoc.Close();

    Response.Write(pdfDoc);

    Response.End();


    }
}

Thanks 谢谢

I almost missed this question because it wasn't tagged as an itext question. 我几乎错过了这个问题,因为它没有被标记为itext问题。

First let me copy/paste/adapt @mkl 's comment: 首先让我复制/粘贴/调整@mkl的评论:

The first part of your code in which you create a document document makes sense. 在其中创建文档document代码的第一部分很有意义。 The second part in which you create a document pdfDoc does not. 创建文档pdfDoc的第二部分则没有。 First of all, at the end of the first part you write the pdf to the response. 首先,在第一部分的末尾,您将pdf写入响应。 That PDF is complete. 该PDF已完成。 It's finished. 都结束了。 It's done. 完成。 It's ready to send to the browser. 准备发送到浏览器。

Why do you think anything additional written to the response thereafter might have a chance of combining with the original written data to a properly generated PDF? 您为什么认为此后在响应中写入的任何其他内容都可能有机会与原始写入的数据合并为正确生成的PDF?

Also: the second part of your code is written as if you want to create a new PDF from scratch; 另外:代码的第二部分就像您要从头开始创建新的PDF一样; but didn't you want to manipulate the PDF created in the first part? 但是您是否不想操纵在第一部分中创建的PDF?

All of this is true, but it doesn't solve your problem. 所有这些都是正确的,但并不能解决您的问题。 It only reveals your deep lack of understanding in PDF. 它仅显示您对PDF的深入了解。

There are different ways to achieve what you want. 有多种方法可以实现您想要的。 I see that you want to use an image as a background of all the pages of a newly created PDF. 我看到您想将图像用作新创建的PDF所有页面的背景。 In that case, you should create a page event, and add that image underneath all the existing content in the OnEndPage() method. 在这种情况下,您应该创建一个页面事件,并将该图像添加到OnEndPage()方法中所有现有内容的下方 This is explained in the answer to How can I add an image to all pages of my PDF? 如何将图像添加到PDF的所有页面的答案中对此进行了解释

Create a PDF as is done in the first part of your code, but introduce a page event: 按照代码第一部分的操作创建PDF,但是引入页面事件:

// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.GetInstance(document, stream);
MyEvent event = new MyEvent();
writer.PageEvent = event;
// step 3
document.Open();
// step 4
// Add whatever content you want to add
// step 5
document.Close();

What is the MyEvent class, you might ask? 您可能会问,什么是MyEvent类? Well, that's a class you create yourself like this: 好吧,这是一个您自己创建的类,如下所示:

protected class MyEvent : PdfPageEventHelper {

    Image image;

    public override void OnOpenDocument(PdfWriter writer, Document document) {
        image = Image.GetInstance(Server.MapPath("~/images/background.png"));
        image.SetAbsolutePosition(0, 0);
    }

    public override void OnEndPage(PdfWriter writer, Document document) {
        writer.DirectContent.AddImage(image);
    }
}

Suppose that your requirement isn't as easy as adding an image in the background, then you could use the bytes created as output to create a PdfReader instance. 假设您的需求不像在后台添加图像那么容易,那么您可以使用作为output创建的字节来创建PdfReader实例。 You could then use the PdfReader to create a PdfStamper and you can use the PdfStamper to watermark the original document. 然后,您可以使用PdfReader创建一个PdfStamper并且可以使用PdfStamper给原始文档加水印。 If the simple solution doesn't meet your needs, create a new question that involves PdfReader / PdfStamper and don't forget to tag that question as an iText question. 如果简单的解决方案不能满足您的需求,请创建一个涉及PdfReader / PdfStamper的新问题,并且不要忘记将该问题标记为iText问题。 (And also: please read the documentation. A lot of time was spent on the iText web site. That time was wasted if you don't consult it.) (另外:请阅读文档。在iText网站上花费了大量时间。如果不咨询的话,那是浪费时间。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM