示例代码:
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace MergePDFs
{
class Program
{
static void Main(string[] args)
{
try
{
int f = 1;
// we create a reader for a certain document
PdfReader reader = new PdfReader(args[f]);
// we retrieve the total number of pagse
int n = reader.NumberOfPages;
Console.WriteLine("There are " + n + " pages in the original file.");
// step 1: creation of a document-object
Document document = new Document(reader.GetPageSizeWithRotation(1));
Console.WriteLine("PS: " + reader.GetPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
String destinationFile = args[0];//The first argument is the destination
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
// step 3: we open the document
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
// step 4: we add content
while (f < args.Length)
{
int i = 0;
while (i < n)
{
i++;
//document.SetPageSize(reader.GetPageSizeWithRotation(i));
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
Console.WriteLine("Processed page " + i);
}
f++;
if (f < args.Length)
{
reader = new PdfReader(args[f]);
// we retrieve the total number of pages
n = reader.NumberOfPages;
Console.WriteLine("There are " + n + " pages in the original file.");
}
}
// step 5: we close the document
document.Close();
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.Error.WriteLine(e.StackTrace);
}
}
}
}
我希望这会输出一个与两个文件相同尺寸的文件(在我的情况下是相同的尺寸)。不幸的是,这种情况并没有发生,并且在合并文档周围打印出白色边框。任何帮助将不胜感激。
答案 0 :(得分:1)
原始PDF完全有可能除了媒体盒之外还有裁剪框。
如果你真的只想复制文件A&amp; B进入文件C,使用PdfCopy。
来自http://itextpdf.com/examples/iia.php?id=123
String[] files = { MovieLinks1.RESULT, MovieHistory.RESULT };
// step 1
Document document = new Document();
// step 2
PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT));
// step 3
document.open();
// step 4
PdfReader reader;
int n;
// loop over the documents you want to concatenate
for (int i = 0; i < files.length; i++) {
reader = new PdfReader(files[i]);
// loop over the pages in that document
n = reader.getNumberOfPages();
for (int page = 0; page < n; ) {
copy.addPage(copy.getImportedPage(reader, ++page));
}
}
// step 5
document.close();
此技术将保留注释(包括字段,但如果要在PROPERLY周围移动字段,则应该使用PdfCopyFields),而不是书签。我不确定层......我想是的。
哦,你可能想在完成每一个之后添加copy.freeReader(reader)
...特别是如果你计划循环使用它们的话。
答案 1 :(得分:0)
尝试
cb.AddTemplate(page, 0, 0);