如何在另一个写入后在pdf上保持相同的格式

时间:2013-02-03 07:23:17

标签: c# itextsharp

我的代码从Pdf中读取文本并将其写入另一个Pdf并进行一些修改,但第二个Pdf中的格式不一样,所以如何保持相同的格式和样式?

我的代码是:

string newFile = @"D:\Result.pdf";
            string file = @"D:\Source.pdf";

            string imagepath = @"D:\logo.jpg";
            Console.WriteLine("Welcome");

            string content="";
            // open the reader
            PdfReader reader = new PdfReader(file);
            iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
            Document document = new Document(size);

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

            int n = reader.NumberOfPages;

            bool addimage = false;
            if (!File.Exists(file))
            {
                file = Path.GetFullPath(file);
                if (!File.Exists(file))
                {
                    Console.WriteLine("Please give in the path to the PDF file.");
                }
            }
            document.Open();
            for (int i = 1; i < n; i++)
            {
                while (addimage == false)
                {
                    iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(imagepath);
                    pic.ScaleToFit(100f, 100f);
                    //pic.ScalePercent(24f);
                    pic.SetAbsolutePosition(document.PageSize.Width - 100f - 100f, document.PageSize.Height + 100f - 225f);
                    document.Add(pic);
                    addimage = true;
                }
                content=PdfTextExtractor.GetTextFromPage(reader, i);
                document.Add(new Paragraph(content));
                PdfContentByte cb = writer.DirectContent;
                cb.MoveTo(document.PageSize.Width / 2, document.PageSize.Height / 2);
                cb.LineTo(document.PageSize.Width / 2, document.PageSize.Height);
                cb.Stroke();
            }
            document.Close(); 
        }

1 个答案:

答案 0 :(得分:2)

请下载chapter 6 of my book并查看表6.1。你会发现你使用了错误的类来复制内容。如果你想要的只是添加一个额外的页面作为现有PDF的封面(这就是我解释你的代码的方式),你应该使用PdfStamper代替PdfCopy。但是,如果你打算在内容为reflow的意义上编辑PDF,请阅读第6章的介绍:PDF不是一种专为编辑而设计的格式。

请注意,本书中的示例是用Java编写的。我们已在SourceForge上发布了这些示例的C#版本。

相关问题