是否有一个PDF文档追加到另一个使用iTextSharp的一个直接的方式? [英] Is there a straight forward way to append one PDF doc to another using iTextSharp?

查看:378
本文介绍了是否有一个PDF文档追加到另一个使用iTextSharp的一个直接的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经冲刷网页寻找如何做到这一点的例子。我发现了一些,似乎是一个涉及多一点,然后他们需要。所以我的问题是,使用iTextSharp的,是有一个PDF文件追加到另外一个相当简洁的方式?

I've scoured the Web looking for examples on how to do this. I've found a few that seem to be a little more involved then they need to be. So my question is, using iTextSharp, is there a fairly concise way to append one PDF document to another one?

最理想的,这将不涉及第三个文件。只要打开第一个PDF文档,第二PDF文档附加到第一,然后关闭它们。

Optimally this would NOT involve a third file. Just open the first PDF doc, append the second PDF doc to the first and then close them both.

推荐答案

好吧,这不是直线前进,但它的工作原理是出奇的快。 (它采用了第三档,没有这样的东西打开并追加)在docs /例子我发现这一点。下面的代码:

Ok, It's not straight forward, but it works and is surprisingly fast. (And it uses a 3rd file, no such thing as open and append.) I 'discovered' this in the docs/examples. Here's the code:

private void CombineMultiplePDFs( string[] fileNames, string outFile ) {
	int pageOffset = 0;
	ArrayList master = new ArrayList();
	int f = 0;

	Document document = null;
	PdfCopy writer = null;
	while ( f < fileNames.Length ) {
		// we create a reader for a certain document
		PdfReader reader = new PdfReader( fileNames[ f ] );
		reader.ConsolidateNamedDestinations();
		// we retrieve the total number of pages
		int n = reader.NumberOfPages;
		ArrayList bookmarks = SimpleBookmark.GetBookmark( reader );
		if ( bookmarks != null ) {
			if ( pageOffset != 0 ) {
				SimpleBookmark.ShiftPageNumbers( bookmarks, pageOffset, null );
			}
			master.AddRange( bookmarks );
		}
		pageOffset += n;

		if ( f == 0 ) {
			// step 1: creation of a document-object
			document = new Document( reader.GetPageSizeWithRotation( 1 ) );
			// step 2: we create a writer that listens to the document
			writer = new PdfCopy( document, new FileStream( outFile, FileMode.Create ) );
			// step 3: we open the document
			document.Open();
		}
		// step 4: we add content
		for ( int i = 0; i < n; ) {
			++i;
			if ( writer != null ) {
				PdfImportedPage page = writer.GetImportedPage( reader, i );
				writer.AddPage( page );
			}
		}
		PRAcroForm form = reader.AcroForm;
		if ( form != null && writer != null ) {
			writer.CopyAcroForm( reader );
		}
		f++;
	}
	if ( master.Count > 0 && writer != null ) {
		writer.Outlines = master;
	}
	// step 5: we close the document
	if ( document != null ) {
		document.Close();
	}
}

这篇关于是否有一个PDF文档追加到另一个使用iTextSharp的一个直接的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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