C#でPDFドキュメントを結合する
概要
この記事では、異なるPDFファイルを1つのPDFにマージ、結合、または連結する方法をC#で説明します。以下のトピックをカバーしています。
ファイルパスを使用してPDFファイルを連結
PdfFileEditorは、複数のPDFファイルを連結することを可能にするAspose.Pdf.Facades namespace内のクラスです。 ファイルを FileStreams を使用して連結するだけでなく、MemoryStreams を使用して連結することもできます。この記事では、MemoryStreams を使用してファイルを連結するプロセスについて説明し、コードスニペットを使用して示します。
PdfFileEditor クラスの Concatenate メソッドを使用して、2 つの PDF ファイルを連結することができます。Concatenate メソッドでは、3 つのパラメータを渡すことができます: 最初の入力 PDF、2 番目の入力 PDF、および出力 PDF。最終的な出力 PDF には、両方の入力 PDF ファイルが含まれます。
次の C# コードスニペットは、ファイルパスを使用して PDF ファイルを連結する方法を示しています。
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.Pdf-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Pages(); | |
// Create PdfFileEditor object | |
PdfFileEditor pdfEditor = new PdfFileEditor(); | |
// Concatenate files | |
pdfEditor.Concatenate(dataDir + "input.pdf", dataDir + "input2.pdf", dataDir + "ConcatenateUsingPath_out.pdf"); |
場合によっては、アウトラインが多い場合、ユーザーは CopyOutlines を false に設定してアウトラインを無効にし、連結のパフォーマンスを向上させることがあります。
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.Pdf-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Pages(); | |
PdfFileEditor pfe = new PdfFileEditor(); | |
string[] files = Directory.GetFiles(dataDir); | |
pfe.CopyOutlines = false; | |
pfe.Concatenate(files, dataDir + "CopyOutline_out.pdf"); |
MemoryStreamを使用して複数のPDFファイルを結合する
PdfFileEditor クラスの Concatenate メソッドは、ソースPDFファイルと宛先PDFファイルをパラメータとして受け取ります。これらのパラメータはディスク上のPDFファイルへのパスであるか、またはMemoryStreamである可能性があります。この例では、最初にディスクからPDFファイルを読み取るための2つのファイルストリームを作成します。そして、これらのファイルをバイト配列に変換します。PDFファイルのこれらのバイト配列はMemoryStreamに変換されます。PDFファイルからMemoryStreamを取得したら、それらを結合メソッドに渡して1つの出力ファイルにマージできるようになります。
以下のC#コードスニペットは、MemoryStreamを使用して複数のPDFファイルを結合する方法を示しています。
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.Pdf-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles(); | |
// Create two file streams to read pdf files | |
FileStream fs1 = new FileStream(dataDir + "inFile.pdf", FileMode.Open, FileAccess.Read); | |
FileStream fs2 = new FileStream(dataDir + "inFile2.pdf", FileMode.Open, FileAccess.Read); | |
// Create byte arrays to keep the contents of PDF files | |
byte[] buffer1 = new byte[Convert.ToInt32(fs1.Length)]; | |
byte[] buffer2 = new byte[Convert.ToInt32(fs2.Length)]; | |
int i = 0; | |
// Read PDF file contents into byte arrays | |
i = fs1.Read(buffer1, 0, Convert.ToInt32(fs1.Length)); | |
i = fs2.Read(buffer2, 0, Convert.ToInt32(fs2.Length)); | |
// Now, first convert byte arrays into MemoryStreams and then concatenate those streams | |
using (MemoryStream pdfStream = new MemoryStream()) | |
{ | |
using (MemoryStream fileStream1 = new MemoryStream(buffer1)) | |
{ | |
using (MemoryStream fileStream2 = new MemoryStream(buffer2)) | |
{ | |
// Create instance of PdfFileEditor class to concatenate streams | |
PdfFileEditor pdfEditor = new PdfFileEditor(); | |
// Concatenate both input MemoryStreams and save to putput MemoryStream | |
pdfEditor.Concatenate(fileStream1, fileStream2, pdfStream); | |
// Convert MemoryStream back to byte array | |
byte[] data = pdfStream.ToArray(); | |
// Create a FileStream to save the output PDF file | |
FileStream output = new FileStream(dataDir + "merged_out.pdf", FileMode.Create, | |
FileAccess.Write); | |
// Write byte array contents in the output file stream | |
output.Write(data, 0, data.Length); | |
// Close output file | |
output.Close(); | |
} | |
} | |
} | |
// Close input files | |
fs1.Close(); | |
fs2.Close(); |
ファイルパスを使用してPDFファイルの配列を連結する
複数のPDFファイルを連結したい場合は、PDFファイルの配列を渡すことができるConcatenateメソッドのオーバーロードを使用できます。最終的な出力は、配列内のすべてのファイルから作成されたマージファイルとして保存されます。次のC#コードスニペットは、ファイルパスを使用してPDFファイルの配列を連結する方法を示しています。
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.Pdf-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Pages(); | |
// Create PdfFileEditor object | |
PdfFileEditor pdfEditor = new PdfFileEditor(); | |
// Array of files | |
string[] filesArray = new string[2]; | |
filesArray[0] = dataDir + "input.pdf"; | |
filesArray[1] = dataDir + "input2.pdf"; | |
// Concatenate files | |
pdfEditor.Concatenate(filesArray, dataDir + "ConcatenateArrayOfFilesWithPath_out.pdf"); |
ストリームを使用してPDFファイルの配列を連結する
PDFファイルの配列を連結することは、ディスク上に存在するファイルに限定されません。 配列のPDFファイルをストリームから連結することもできます。複数のPDFファイルを連結したい場合は、Concatenateメソッドの適切なオーバーロードを使用できます。まず、入力ストリームの配列と出力PDF用のストリームを作成し、次にConcatenateメソッドを呼び出します。出力は出力ストリームに保存されます。以下のC#コードスニペットは、ストリームを使用してPDFファイルの配列を連結する方法を示しています。
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.Pdf-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Pages(); | |
// Create PdfFileEditor object | |
PdfFileEditor pdfEditor = new PdfFileEditor(); | |
// Output stream | |
FileStream outputStream = new FileStream(dataDir + "ConcatenateArrayOfPdfUsingStreams_out.pdf", FileMode.Create); | |
// Array of streams | |
FileStream[] inputStreams = new FileStream[2]; | |
inputStreams[0] = new FileStream(dataDir + "input.pdf", FileMode.Open); | |
inputStreams[1] = new FileStream(dataDir + "input2.pdf", FileMode.Open); | |
// Concatenate file | |
pdfEditor.Concatenate(inputStreams, outputStream); |
特定のフォルダー内のすべてのPdfファイルを連結する
実行時に特定のフォルダー内のすべてのPdfファイルを読み取り、ファイル名を知らなくてもそれらを連結することができます。 ディレクトリのパスを指定してください。そこには、結合したいPDFドキュメントが含まれています。
この機能を達成するために、次のC#コードスニペットを試してみてください。
PDFフォームを結合し、フィールド名をユニークに保つ
Aspose.Pdf.Facades namespace の PdfFileEditor クラスは、PDFファイルを結合する機能を提供します。 Now, if the Pdf files which are to be concatenated have form fields with similar field names, Aspose.PDF provides the feature to keep the fields in the resultant Pdf file as unique and also you can specify the suffix to make the field names unique. KeepFieldsUnique プロパティの PdfFileEditor を true に設定すると、Pdf フォームを連結する際にフィールド名がユニークになります。また、PdfFileEditor の UniqueSuffix プロパティを使用して、フォームを連結する際にフィールド名をユニークにするために追加されるサフィックスのユーザー定義フォーマットを指定できます。この文字列には %NUM%
サブストリングを含める必要があり、結果ファイルで数字に置き換えられます。
この機能を実現するための簡単なコードスニペットを以下に示します。
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.Pdf-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles(); | |
// Set input and output file paths | |
string inputFile1 = dataDir + "inFile1.pdf"; | |
string inputFile2 = dataDir + "inFile2.pdf"; | |
string outFile = dataDir + "ConcatenatePDFForms_out.pdf"; | |
// Instantiate PdfFileEditor Object | |
PdfFileEditor fileEditor = new PdfFileEditor(); | |
// To keep unique field Id for all the fields | |
fileEditor.KeepFieldsUnique = true; | |
// Format of the suffix which is added to field name to make it unique when forms are concatenated. | |
fileEditor.UniqueSuffix = "_%NUM%"; | |
// Concatenate the files into a resultant Pdf file | |
fileEditor.Concatenate(inputFile1, inputFile2, outFile); |
PDFファイルを連結して目次を作成
PDFファイルを連結
PDFファイルをマージする方法については、次のコードスニペットをご覧ください。
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.Pdf-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles(); | |
// Create PdfFileEditor object | |
PdfFileEditor pdfEditor = new PdfFileEditor(); | |
// Save concatenated output file | |
pdfEditor.Concatenate(new FileStream(dataDir + "input1.pdf", FileMode.Open), new FileStream(dataDir + "input2.pdf", FileMode.Open), new FileStream(dataDir + "ConcatenatePdfFilesAndCreateTOC_out.pdf", FileMode.Create)); |
空白ページを挿入
PDFファイルがマージされた後、文書の先頭に空白ページを挿入し、そこに目次を作成することができます。この要件を達成するために、マージされたファイルをDocumentオブジェクトにロードし、Page.Insert(…)メソッドを呼び出して空白ページを挿入する必要があります。
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.Pdf-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles(); | |
// Insert a blank page at the begining of concatenated file to display Table of Contents | |
Aspose.Pdf.Document concatenated_pdfDocument = new Aspose.Pdf.Document(new FileStream(dataDir + "Concatenated_Table_Of_Contents.pdf", FileMode.Open)); | |
// Insert a empty page in a PDF | |
concatenated_pdfDocument.Pages.Insert(1); |
テキストスタンプを追加
目次を作成するために、PdfFileStampとStampオブジェクトを使用して、最初のページにテキストスタンプを追加する必要があります。 Stamp クラスは FormattedText を追加するための BindLogo(...)
メソッドを提供しており、SetOrigin(..)
メソッドを使用してこれらのテキストスタンプを追加する場所を指定することもできます。この記事では、2 つの PDF ファイルを連結しているため、これらの個々のドキュメントを指す 2 つのテキストスタンプオブジェクトを作成する必要があります。
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.Pdf-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles(); | |
// Set Text Stamp to display string Table Of Contents | |
Aspose.Pdf.Facades.Stamp stamp = new Aspose.Pdf.Facades.Stamp(); | |
stamp.BindLogo(new FormattedText("Table Of Contents", System.Drawing.Color.Maroon, System.Drawing.Color.Transparent, Aspose.Pdf.Facades.FontStyle.Helvetica, EncodingType.Winansi, true, 18)); | |
// Specify the origin of Stamp. We are getting the page width and specifying the X coordinate for stamp | |
stamp.SetOrigin((new PdfFileInfo(new FileStream(dataDir + "input1.pdf", FileMode.Open)).GetPageWidth(1) / 3), 700); | |
// Set particular pages | |
stamp.Pages = new int[] { 1 }; |
ローカルリンクの作成
次に、連結されたファイル内のページへのリンクを追加する必要があります。この要件を達成するために、PdfContentEditor クラスの CreateLocalLink(..)
メソッドを使用することができます。次のコードスニペットでは、4 番目の引数として Transparent を渡して、リンクの周囲の長方形が見えないようにしています。
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.Pdf-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles(); | |
// Now we need to add Heading for Table Of Contents and links for documents | |
PdfContentEditor contentEditor = new PdfContentEditor(); | |
// Bind the PDF file in which we added the blank page | |
contentEditor.BindPdf(new FileStream(dataDir + "Concatenated_Table_Of_Contents.pdf", FileMode.Open)); | |
// Create link for first document | |
contentEditor.CreateLocalLink(new System.Drawing.Rectangle(150, 650, 100, 20), 2, 1, System.Drawing.Color.Transparent); |
完全なコード
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.Pdf-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles(); | |
// Create PdfFileEditor object | |
PdfFileEditor pdfEditor = new PdfFileEditor(); | |
// Create a MemoryStream object to hold the resultant PDf file | |
using (MemoryStream Concatenated_Stream = new MemoryStream()) | |
{ | |
// Save concatenated output file | |
pdfEditor.Concatenate(new FileStream(dataDir + "input1.pdf", FileMode.Open), new FileStream(dataDir + "input2.pdf", FileMode.Open), Concatenated_Stream); | |
// Insert a blank page at the begining of concatenated file to display Table of Contents | |
Aspose.Pdf.Document concatenated_pdfDocument = new Aspose.Pdf.Document(Concatenated_Stream); | |
// Insert a empty page in a PDF | |
concatenated_pdfDocument.Pages.Insert(1); | |
// Hold the resultnat file with empty page added | |
using (MemoryStream Document_With_BlankPage = new MemoryStream()) | |
{ | |
// Save output file | |
concatenated_pdfDocument.Save(Document_With_BlankPage); | |
using (var Document_with_TOC_Heading = new MemoryStream()) | |
{ | |
// Add Table Of Contents logo as stamp to PDF file | |
PdfFileStamp fileStamp = new PdfFileStamp(); | |
// Find the input file | |
fileStamp.BindPdf(Document_With_BlankPage); | |
// Set Text Stamp to display string Table Of Contents | |
Aspose.Pdf.Facades.Stamp stamp = new Aspose.Pdf.Facades.Stamp(); | |
stamp.BindLogo(new FormattedText("Table Of Contents", System.Drawing.Color.Maroon, System.Drawing.Color.Transparent, Aspose.Pdf.Facades.FontStyle.Helvetica, EncodingType.Winansi, true, 18)); | |
// Specify the origin of Stamp. We are getting the page width and specifying the X coordinate for stamp | |
stamp.SetOrigin((new PdfFileInfo(Document_With_BlankPage).GetPageWidth(1) / 3), 700); | |
// Set particular pages | |
stamp.Pages = new int[] { 1 }; | |
// Add stamp to PDF file | |
fileStamp.AddStamp(stamp); | |
// Create stamp text for first item in Table Of Contents | |
var Document1_Link = new Aspose.Pdf.Facades.Stamp(); | |
Document1_Link.BindLogo(new FormattedText("1 - Link to Document 1", System.Drawing.Color.Black, System.Drawing.Color.Transparent, Aspose.Pdf.Facades.FontStyle.Helvetica, EncodingType.Winansi, true, 12)); | |
// Specify the origin of Stamp. We are getting the page width and specifying the X coordinate for stamp | |
Document1_Link.SetOrigin(150, 650); | |
// Set particular pages on which stamp should be displayed | |
Document1_Link.Pages = new int[] { 1 }; | |
// Add stamp to PDF file | |
fileStamp.AddStamp(Document1_Link); | |
// Create stamp text for second item in Table Of Contents | |
var Document2_Link = new Aspose.Pdf.Facades.Stamp(); | |
Document2_Link.BindLogo(new FormattedText("2 - Link to Document 2", System.Drawing.Color.Black, System.Drawing.Color.Transparent, Aspose.Pdf.Facades.FontStyle.Helvetica, EncodingType.Winansi, true, 12)); | |
// Specify the origin of Stamp. We are getting the page width and specifying the X coordinate for stamp | |
Document2_Link.SetOrigin(150, 620); | |
// Set particular pages on which stamp should be displayed | |
Document2_Link.Pages = new int[] { 1 }; | |
// Add stamp to PDF file | |
fileStamp.AddStamp(Document2_Link); | |
// Save updated PDF file | |
fileStamp.Save(Document_with_TOC_Heading); | |
fileStamp.Close(); | |
// Now we need to add Heading for Table Of Contents and links for documents | |
PdfContentEditor contentEditor = new PdfContentEditor(); | |
// Bind the PDF file in which we added the blank page | |
contentEditor.BindPdf(Document_with_TOC_Heading); | |
// Create link for first document | |
contentEditor.CreateLocalLink(new System.Drawing.Rectangle(150, 650, 100, 20), 2, 1, System.Drawing.Color.Transparent); | |
// Create link for Second document | |
// We have used new PdfFileInfo("d:/pdftest/Input1.pdf").NumberOfPages + 2 as PdfFileInfo.NumberOfPages(..) returns the page count for first document | |
// And 2 is because, second document will start at Input1+1 and 1 for the page containing Table Of Contents. | |
contentEditor.CreateLocalLink(new System.Drawing.Rectangle(150, 620, 100, 20), new PdfFileInfo(dataDir + "Input1.pdf").NumberOfPages + 2, 1, System.Drawing.Color.Transparent); | |
// Save updated PDF | |
contentEditor.Save( dataDir + "Concatenated_Table_Of_Contents.pdf"); | |
} | |
} | |
} |
フォルダ内のPDFファイルを連結する
Aspose.Pdf.Facades名前空間のPdfFileEditorクラスは、PDFファイルを連結する機能を提供します。特定のフォルダ内のすべてのPDFファイルを実行時に読み込んで連結することができ、ファイル名を知る必要もありません。連結したいPDFドキュメントを含むディレクトリのパスを指定するだけです。
この機能をAspose.PDFで実現するために、次のC#コードスニペットを使用してみてください:
// ドキュメントディレクトリへのパス。
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles();
// 特定のディレクトリ内のすべてのPdfファイルの名前を取得
string[] fileEntries = Directory.GetFiles(dataDir, "*.pdf");
// 現在のシステム日付を取得し、そのフォーマットを設定
string date = DateTime.Now.ToString("MM-dd-yyyy");
// 現在のシステム時間を取得し、そのフォーマットを設定
string hoursSeconds = DateTime.Now.ToString("hh-mm");
// 最終的な結果のPdfドキュメントの値を設定
string masterFileName = date + "_" + hoursSeconds + "_out.pdf";
// PdfFileEditorオブジェクトをインスタンス化
Aspose.Pdf.Facades.PdfFileEditor pdfEditor = new PdfFileEditor();
// PdfFileEditorオブジェクトのConcatenateメソッドを呼び出し、すべての入力ファイルを単一の出力ファイルに連結
pdfEditor.Concatenate(fileEntries, dataDir + masterFileName);