如何使用iTextSharp加入两个PDF? [英] How can I join two PDF's using iTextSharp?

查看:117
本文介绍了如何使用iTextSharp加入两个PDF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用本教程作为base,但它在下面指定的行处抛出一个空引用异常。我应该以不同的方式做这件事吗?如果没有,为什么它会抛出一个空引用异常( page cb 都不为null)。代码:

I tried to do it using this tutorial as a base, but it's throwing a null reference exception at the line specified below. Should I be doing this a different way? If not, why would it throw an null reference exception (both page and cb are NOT null). Code:

        string filePath = @"c:\temp\test_new.pdf";
        string attachPath = @"c:\temp\test.pdf";

        Console.WriteLine("Begin!");
        Document d = new Document();

        if(File.Exists(filePath)){File.Delete(filePath);}

        FileStream fs = new FileStream(filePath, FileMode.Create);

        PdfWriter pw = PdfWriter.GetInstance(d, fs);
        d.Open();
        d.Add(new Paragraph("New document!  Now lets add an attachment!"));

        PdfReader pRdr = new PdfReader(new FileStream(attachPath,FileMode.Open));
        PdfReaderContentParser parser = new PdfReaderContentParser(pRdr);

        MemoryStream ms = new MemoryStream();
        PdfWriter writer = PdfWriter.GetInstance(d, ms);
        writer.Open();
        PdfContentByte cb = writer.DirectContent;
        PdfImportedPage page;
        int rotation;
        d.SetPageSize(PageSize.LETTER);
        for (int i = 1; i <= pRdr.NumberOfPages; i++)
        {
            d.NewPage();
            page = writer.GetImportedPage(pRdr, i);
            rotation = pRdr.GetPageRotation(i);
            if (rotation == 90 || rotation == 270)
            {
                cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, pRdr.GetPageSizeWithRotation(i).Height);
            }
            else
            {
  /*NULL EXCEPTION HERE!!!*/cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0);  //NULL EXCEPTION HERE!!!

            }
        }


推荐答案

1)使用PdfCopy而不是PdfWriter。 PdfWriter用于从Document写入生成的PDF。 PdfCopy用于将页面从A复制到B.

1) Use PdfCopy not PdfWriter. PdfWriter is for writing generated PDFs from a Document. PdfCopy is made for copying pages from A to B.

2)如果问题是异常的结果,请发布异常。它将消除您在评论中看到的大部分猜测。

2) If you're problem is the result of an exception PLEASE post the exception. It'll remove much of the guesswork you see in the comments.

3)PdfImportedPage只是该页面的内容和资源。您丢失了注释(表单字段等),书签等。 PdfCopy可以帮助解决其中一些问题,但不是全部。

3) PdfImportedPage is just that page's contents and resources. You lose annotations (form fields and the like), bookmarks, and so forth. PdfCopy can help with some of that, but not all.

这篇关于如何使用iTextSharp加入两个PDF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆