0

我很难过,需要大师的帮助!

我正在使用 itextsharp 即时编写不想保存到服务器的文本,只需将其放入内存流中并以 pdf 格式显示即可。

我该如何修改此代码。

    var reader = new PdfReader(filePath);
    var size = reader.GetPageSizeWithRotation(1);
    var document = new Document(size);

    var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
    var writer = PdfWriter.GetInstance(document, fs);
    document.Open();

    var cb = writer.DirectContent;

    for (int page = 1; page <= reader.NumberOfPages; page++)
    {
        document.NewPage();
        var importedPage = writer.GetImportedPage(reader, page);
        cb.AddTemplate(importedPage, 0, 0);

        BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.BeginText();
        cb.SetFontAndSize(bf, 10);
        cb.ShowTextAligned(Element.ALIGN_LEFT, lefttext, 50, 400, 90);
        cb.EndText();

        cb.BeginText();
        cb.SetFontAndSize(bf, 10);
        cb.ShowTextAligned(Element.ALIGN_JUSTIFIED_ALL, headertext, 280, 720, 0);
        cb.EndText();

        cb.BeginText();
        cb.SetFontAndSize(bf, 10);
        cb.ShowTextAligned(Element.ALIGN_JUSTIFIED_ALL, footertext, 280, 50, 0);
        cb.EndText();
    }

    document.Close();
    fs.Close();
    writer.Close();
    reader.Close();

我修改了我的代码,但这次它多次将同一页面写入第一页。有什么问题?你能帮帮这个菜鸟吗:(

    var reader = new PdfReader(server.MapPath("~/Data/162013.pdf"));
    using (var ms = new MemoryStream())
    {
        var stamper = new PdfStamper(reader, ms);
        var cb = stamper.GetOverContent(1);
        var size = reader.GetPageSizeWithRotation(1);
        var document = new Document(size);
        document.Open();
        for (var page = 1; page <= reader.NumberOfPages; page++)
        {
            document.NewPage();
            var importedPage = stamper.GetImportedPage(reader, page);
            cb.AddTemplate(importedPage, 0 , 0);

            var bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            cb.BeginText();
            cb.SetFontAndSize(bf, 10);
            cb.ShowTextAligned(Element.ALIGN_LEFT, "sdfdsf", 50, 400, 90);
            cb.EndText();

            cb.BeginText();
            cb.SetFontAndSize(bf, 10);
            cb.ShowTextAligned(Element.ALIGN_JUSTIFIED_ALL, "sdfsdfsd", 280, 720, 0);
            cb.EndText();

            cb.BeginText();
            cb.SetFontAndSize(bf, 10);
            cb.ShowTextAligned(Element.ALIGN_JUSTIFIED_ALL, "sdfsdf", 280, 50, 0);
            cb.EndText();
        }

        stamper.FormFlattening = true;
        document.Close();
        stamper.Close();
        DownloadAsPDF(ms);
    }

}
4

0 回答 0