C# 使用 iTextSharp 创建多页 pdf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11307749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:19:56  来源:igfitidea点击:

Creating multiple page pdf using iTextSharp

c#pdfitextsharp

提问by amesh

I am trying to create pdf with multiple pages using iTextSharp

我正在尝试使用 iTextSharp 创建包含多个页面的 pdf

Document document = new Document(PageSize.A4, 2, 2, 10, 10);
private PdfContentByte _pcb;

try
{
    PdfWriter writer = PdfWriter.GetInstance(document, output);
    document.Open();             
    document.NewPage();
    _pcb = writer.DirectContent;
    _pcb.BeginText();
    _pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, x, y, 0);
    _pcb.EndText();
    writer.Flush();
}
catch(e)
{

}
finally
{
    document.Close();
}

This is working fine for me. When I am trying to add a new page on the same document, it is replacing the existing written text with new page and no new page is getting added. Below is the code which is not working.

这对我来说很好用。当我尝试在同一个文档上添加新页面时,它正在用新页面替换现有的书面文本,并且没有添加新页面。下面是不起作用的代码。

_pcb.EndText();
writer.Flush();
document.NewPage();
_pcb = writer.DirectContent;
_pcb.BeginText();
_pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, x, y, 0);
_pcb.EndText();
writer.Flush();

采纳答案by Chris Haas

Below is my attempt to clean-up and unify your code. Generally avoid try-catch until you actually have to, you'll often miss some very important errors. (For instance, you're not actually setting the font and size which is required but maybe you just omitted that code.) Also, unless you are writing a very large PDF there's really no reason to flush the buffers, leave that to the OS to do for you when necessary.

下面是我尝试清理和统一您的代码。通常避免 try-catch 直到你真的不得不这样做,你经常会错过一些非常重要的错误。(例如,您实际上并没有设置所需的字体和大小,但也许您只是省略了该代码。)此外,除非您正在编写非常大的 PDF,否则真的没有理由刷新缓冲区,将其留给操作系统必要时为你做。

When I run the code below I get two pages with text on both pages, does it work for you? (Targeting iTextSharp 5.2.0.0)

当我运行下面的代码时,我得到两页上都有文本的页面,它对你有用吗?(针对 iTextSharp 5.2.0.0)

        var output = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf");
        var bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
        using (FileStream fs = new FileStream(output, FileMode.Create, FileAccess.Write, FileShare.None)) {
            using (Document doc = new Document(PageSize.A4, 2, 2, 10, 10)) {
                PdfContentByte _pcb;
                using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
                    //Open document for writing
                    doc.Open();
                    //Insert page
                    doc.NewPage();
                    //Alias to DirectContent
                    _pcb = writer.DirectContent;
                    //Set the font and size
                    _pcb.SetFontAndSize(bf, 12);
                    //Show some text
                    _pcb.BeginText();
                    _pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Page 1", 40, 600, 0);
                    _pcb.EndText();
                    //Insert a new page
                    doc.NewPage();
                    //Re-set font and size
                    _pcb.SetFontAndSize(bf, 12);
                    //Show more text on page 2
                    _pcb.BeginText();
                    _pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Page 2", 100, 400, 0);
                    _pcb.EndText();
                    doc.Close();
                }
            }
        }

回答by Alexis Pigeon

Why do you use the DirectContent? If you just want to create a PDF from scratch, just add content to the Document.

你为什么使用DirectContent? 如果您只想从头开始创建 PDF,只需将内容添加到Document.

try
{
    iTextSharp.text.Document doc = new iTextSharp.text.Document();
    PdfWriter.GetInstance(doc, new FileStream("HelloWorld.pdf", FileMode.Create));
    doc.Open();
    doc.Add(new Paragraph("Hello World!"));
    doc.NewPage();
    doc.Add(new Paragraph("Hello World on a new page!"));
}
catch (Exception ex)
{

}
finally 
{
    doc.Close();
}

回答by Singh T

Below Code is working

下面的代码正在工作

string str = "Page1Page1Page1Page1Page1Page1Page1Page1Page1Page1";
string str2 = "Page2Page2Page2Page2Page2Page2Page2Page2Page2Page2";
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
using (var htmlWorker = new HTMLWokExtend(pdfDoc))
{
    using (var sr = new StringReader(str))
    {
        htmlWorker.Parse(sr);
    }
}
pdfDoc.NewPage();
using (var htmlWorker = new HTMLWokExtend(pdfDoc))
{
    using (var sr = new StringReader(str2))
    {
      htmlWorker.Parse(sr);
    }
}
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" +
                               "filename=Proforma_Invoice.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();

You can populate string from HTML body using below function

您可以使用以下函数从 HTML 正文填充字符串

private string populatebody()
{
    string body="";
    using (StreamReader reader = new StreamReader(Server.MapPath("~/Dir/Page.html")))
    {
        body = reader.ReadToEnd();
    }
    body = body.Replace("{Content in htmlpage}", "Your Content");
    return body
}

And then return this body to string in upper code. You can manipulate with this code as per your requirement.

然后将此主体返回到上层代码中的字符串。您可以根据需要使用此代码进行操作。

Below is HTMLWokExtend Class:

下面是 HTMLWokExtend 类:

public class HTMLWokExtend : HTMLWorker
{
    LineSeparator line = new LineSeparator(1f, 90f, BaseColor.GRAY, Element.ALIGN_CENTER, -12);
    public HTMLWokExtend(IDocListener document) : base(document)
    {

    }
    public override void StartElement(string tag, IDictionary<string, string> str)
    {
        if (tag.Equals("hrline"))
            document.Add(new Chunk(line));
        else
            base.StartElement(tag, str);
    }
}