/// <summary> /// Extract a single page from PDF file. /// </summary> /// <param name="sourceFile">The source file.</param> /// <param name="outputFile">The output file.</param> /// <param name="pageNumber">The specific page number.</param> public static void ExtractPage(string sourceFile, string outputFile, int pageNumber) { try { PdfReader reader = new PdfReader(sourceFile); if (pageNumber > reader.NumberOfPages) { Console.WriteLine("This page number is out of reach."); return; } Document document = new Document(); PdfCopy pdfCopy = new PdfCopy(document, new FileStream(outputFile, FileMode.Create)); document.Open(); PdfImportedPage importedPage = pdfCopy.GetImportedPage(reader, pageNumber); pdfCopy.AddPage(importedPage); document.Close(); reader.Close(); } catch (Exception ex) { throw ex; } }
public static bool Collate(string frontSide, string backSide, string saveAs, bool backSideIsInReverseOrder = true) { try { bool backSideIsAscending = !backSideIsInReverseOrder; using (FileStream stream = new FileStream(saveAs, FileMode.Create)) using (Document doc = new Document()) using (PdfCopy pdf = new PdfCopy(doc, stream)) { doc.Open(); int b = 0; using (PdfReader front = new PdfReader(frontSide)) { using (PdfReader back = new PdfReader(backSide)) { for (int p = 1; p <= front.NumberOfPages; p++) { pdf.AddPage(pdf.GetImportedPage(front, p)); pdf.FreeReader(front); if (p <= back.NumberOfPages) { if (backSideIsAscending) b = p; else b = back.NumberOfPages - p + 1; pdf.AddPage(pdf.GetImportedPage(back, b)); pdf.FreeReader(back); } } } } } } catch(Exception ex) { Console.WriteLine(ex.Message); return false; } return true; }
public void ConvertToImage(string _rutaPDF, int width, int height) { iTextSharp.text.pdf.PdfReader reader = null; int currentPage = 1; int pageCount = 0; System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); reader = new iTextSharp.text.pdf.PdfReader(_rutaPDF); reader.RemoveUnusedObjects(); pageCount = reader.NumberOfPages; string ext = System.IO.Path.GetExtension(_rutaPDF); for (int i = 1; i <= 1; i++) { iTextSharp.text.pdf.PdfReader reader1 = new iTextSharp.text.pdf.PdfReader(_rutaPDF); string outfile = _rutaPDF.Replace((System.IO.Path.GetFileName(_rutaPDF)), (System.IO.Path.GetFileName(_rutaPDF).Replace(".pdf", "") + "_" + i.ToString()) + ext); reader1.RemoveUnusedObjects(); iTextSharp.text.Document doc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage)); iTextSharp.text.pdf.PdfCopy pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.Create)); doc.Open(); for (int j = 1; j <= 1; j++) { iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader1, currentPage); pdfCpy.SetFullCompression(); pdfCpy.AddPage(page); currentPage += 1; } doc.Close(); pdfCpy.Close(); reader1.Close(); reader.Close(); } }
public void MergePDFs(string outPutFilePath, params string[] filesPath) { try { List <PdfReader> readerList = new List <PdfReader>(); foreach (string filePath in filesPath) { PdfReader pdfReader = new PdfReader(filePath); readerList.Add(pdfReader); } iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0f, 0f, 0f, 20f); iTextSharp.text.pdf.PdfCopy writer = new iTextSharp.text.pdf.PdfCopy(document, new System.IO.FileStream(outPutFilePath, System.IO.FileMode.Create)); document.Open(); foreach (PdfReader reader in readerList) { for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); document.Add(iTextSharp.text.Image.GetInstance(page)); } writer.AddDocument(reader); reader.Close(); } document.Close(); writer.Close(); } catch (Exception ex) { ex.ToString(); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { // Use previous examples to create PDF files MovieLinks1 m = new MovieLinks1(); byte[] pdfM = Utility.PdfBytes(m); LinkActions l = new LinkActions(); byte[] pdfL = l.CreatePdf(); // Create readers. PdfReader[] readers = { new PdfReader(pdfL), new PdfReader(pdfM) }; // step 1 //Document document = new Document(); // step 2 using (var ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { using (PdfCopy copy = new PdfCopy(document, ms)) { // step 3 document.Open(); // step 4 int n; // copy the pages of the different PDFs into one document for (int i = 0; i < readers.Length; i++) { readers[i].ConsolidateNamedDestinations(); n = readers[i].NumberOfPages; for (int page = 0; page < n; ) { copy.AddPage(copy.GetImportedPage(readers[i], ++page)); } } // Add named destination copy.AddNamedDestinations( // from the second document SimpleNamedDestination.GetNamedDestination(readers[1], false), // using the page count of the first document as offset readers[0].NumberOfPages ); } zip.AddEntry(RESULT1, ms.ToArray()); } // Create a reader PdfReader reader = new PdfReader(ms.ToArray()); // Convert the remote destinations into local destinations reader.MakeRemoteNamedDestinationsLocal(); using (MemoryStream ms2 = new MemoryStream()) { // Create a new PDF containing the local destinations using (PdfStamper stamper = new PdfStamper(reader, ms2)) { } zip.AddEntry(RESULT2, ms2.ToArray()); } } zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdfM); zip.AddEntry(Utility.ResultFileName(l.ToString() + ".pdf"), pdfL); zip.Save(stream); } }
public void TestExtraXObjects() { #if DRAWING PdfReader sourceR = new PdfReader(CreateImagePdf()); try { int sourceXRefCount = sourceR.XrefSize; Document document = new Document(); MemoryStream outStream = new MemoryStream(); PdfCopy copy = new PdfCopy(document, outStream); document.Open(); PdfImportedPage importedPage = copy.GetImportedPage(sourceR, 1); copy.AddPage(importedPage); document.Close(); PdfReader targetR = new PdfReader(outStream.ToArray()); int destinationXRefCount = targetR.XrefSize; // TestResourceUtils.saveBytesToFile(createImagePdf(), new File("./source.pdf")); // TestResourceUtils.saveBytesToFile(out.toByteArray(), new File("./result.pdf")); Assert.AreEqual(sourceXRefCount, destinationXRefCount); } finally { sourceR.Close(); } #endif// DRAWING }
public void ExtractPage(string sourcePdfPath, string outputPdfPath, int pageNumber, string password = "") { PdfReader reader = null; Document document = null; PdfCopy pdfCopyProvider = null; PdfImportedPage importedPage = null; try { // Intialize a new PdfReader instance with the contents of the source Pdf file: reader = new PdfReader(sourcePdfPath, Encoding.UTF8.GetBytes(password)); // Capture the correct size and orientation for the page: document = new Document(reader.GetPageSizeWithRotation(pageNumber)); // Initialize an instance of the PdfCopyClass with the source // document and an output file stream: pdfCopyProvider = new PdfCopy(document, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create)); document.Open(); // Extract the desired page number: importedPage = pdfCopyProvider.GetImportedPage(reader, pageNumber); pdfCopyProvider.AddPage(importedPage); document.Close(); reader.Close(); } catch (Exception ex) { throw ex; } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // use one of the previous examples to create a PDF MovieTemplates mt = new MovieTemplates(); // Create a reader byte[] pdf = Utility.PdfBytes(mt); PdfReader reader = new PdfReader(pdf); // loop over all the pages in the original PDF int n = reader.NumberOfPages; using (ZipFile zip = new ZipFile()) { for (int i = 0; i < n; ) { string dest = string.Format(RESULT, ++i); using (MemoryStream ms = new MemoryStream()) { // We'll create as many new PDFs as there are pages // step 1 using (Document document = new Document()) { // step 2 using (PdfCopy copy = new PdfCopy(document, ms)) { // step 3 document.Open(); // step 4 copy.AddPage(copy.GetImportedPage(reader, i)); } } zip.AddEntry(dest, ms.ToArray()); } } zip.AddEntry(Utility.ResultFileName(mt.ToString() + ".pdf"), pdf); zip.Save(stream); } }
/** * Creates an instance of the concatenation class. * @param os the Stream for the PDF document * @param smart do we want PdfCopy to detect redundant content? */ public PdfConcatenate(Stream os, bool smart) { document = new Document(); if (smart) copy = new PdfSmartCopy(document, os); else copy = new PdfCopy(document, os); }
// --------------------------------------------------------------------------- public void Write(Stream stream) { MovieLinks1 ml = new MovieLinks1(); MovieHistory mh = new MovieHistory(); List<byte[]> pdf = new List<byte[]>() { Utility.PdfBytes(ml), Utility.PdfBytes(mh) }; string[] names = {ml.ToString(), mh.ToString()}; using (ZipFile zip = new ZipFile()) { using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { // step 2 using (PdfCopy copy = new PdfCopy(document, ms)) { // step 3 document.Open(); // step 4 for (int i = 0; i < pdf.Count; ++i) { zip.AddEntry(Utility.ResultFileName(names[i] + ".pdf"), pdf[i]); PdfReader reader = new PdfReader(pdf[i]); // loop over the pages in that document int n = reader.NumberOfPages; for (int page = 0; page < n; ) { copy.AddPage(copy.GetImportedPage(reader, ++page)); } } } } zip.AddEntry(RESULT, ms.ToArray()); } zip.Save(stream); } }
public void Combine(string saveFileName, IEnumerable<string> files) { byte[] mergedPdf = null; using (MemoryStream ms = new MemoryStream()) { using (Document document = new Document()) { using (PdfCopy copy = new PdfCopy(document, ms)) { document.Open(); foreach (var item in files.OrderBy(x=> x)) { PdfReader reader = new PdfReader(item); // loop over the pages in that document int n = reader.NumberOfPages; for (int page = 0; page < n; ) { copy.AddPage(copy.GetImportedPage(reader, ++page)); } reader.Close(); } } } mergedPdf = ms.ToArray(); } File.WriteAllBytes(String.Concat(saveFileName, ".pdf"), mergedPdf); }
/// <summary> /// Merges multiple pdf files into 1 pdf file. /// </summary> /// <param name="FilesToMerge">Files to merger (Byte array for each file)</param> /// <returns>1 file with all the files passed in</returns> public static byte[] MergeFiles(IEnumerable<byte[]> FilesToMerge) { //Declare the memory stream to use using (var MemoryStreamToWritePdfWith = new MemoryStream()) { //declare the new document which we will merge all the files into using (var NewFileToMergeIntoWith = new Document()) { //holds the byte array which we will return byte[] ByteArrayToReturn; //declare the pdf copy to write the data with using (var PdfCopyWriter = new PdfCopy(NewFileToMergeIntoWith, MemoryStreamToWritePdfWith)) { //set the page size of the new file //NewFileToMergeIntoWith.SetPageSize(PageSize.GetRectangle("Letter").Rotate().Rotate()); //go open the new file that we are writing into NewFileToMergeIntoWith.Open(); //now loop through all the files we want to merge foreach (var FileToMerge in FilesToMerge) { //declare the pdf reader so we can copy it using (var PdfFileReader = new PdfReader(FileToMerge)) { //figure out how many pages are in this pdf, so we can add each of the pdf's int PdfFilePageCount = PdfFileReader.NumberOfPages; // loop over document pages (start with page 1...not a 0 based index) for (int i = 1; i <= PdfFilePageCount; i++) { //set the file size for this page NewFileToMergeIntoWith.SetPageSize(PdfFileReader.GetPageSize(i)); //add a new page for the next page NewFileToMergeIntoWith.NewPage(); //now import the page PdfCopyWriter.AddPage(PdfCopyWriter.GetImportedPage(PdfFileReader, i)); } } } //now close the new file which we merged everyting into NewFileToMergeIntoWith.Close(); //grab the buffer and throw it into a byte array to return ByteArrayToReturn = MemoryStreamToWritePdfWith.GetBuffer(); //flush out the memory stream MemoryStreamToWritePdfWith.Flush(); } //now return the byte array return ByteArrayToReturn; } } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { MovieLinks1 ml = new MovieLinks1(); byte[] r1 = Utility.PdfBytes(ml); MovieHistory mh = new MovieHistory(); byte[] r2 = Utility.PdfBytes(mh); using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { // step 2 using (PdfCopy copy = new PdfCopy(document, ms)) { // step 3 document.Open(); // step 4 // reader for document 1 PdfReader reader1 = new PdfReader(r1); int n1 = reader1.NumberOfPages; // reader for document 2 PdfReader reader2 = new PdfReader(r2); int n2 = reader2.NumberOfPages; // initializations PdfImportedPage page; PdfCopy.PageStamp stamp; // Loop over the pages of document 1 for (int i = 0; i < n1; ) { page = copy.GetImportedPage(reader1, ++i); stamp = copy.CreatePageStamp(page); // add page numbers ColumnText.ShowTextAligned( stamp.GetUnderContent(), Element.ALIGN_CENTER, new Phrase(string.Format("page {0} of {1}", i, n1 + n2)), 297.5f, 28, 0 ); stamp.AlterContents(); copy.AddPage(page); } // Loop over the pages of document 2 for (int i = 0; i < n2; ) { page = copy.GetImportedPage(reader2, ++i); stamp = copy.CreatePageStamp(page); // add page numbers ColumnText.ShowTextAligned( stamp.GetUnderContent(), Element.ALIGN_CENTER, new Phrase(string.Format("page {0} of {1}", n1 + i, n1 + n2)), 297.5f, 28, 0 ); stamp.AlterContents(); copy.AddPage(page); } } } zip.AddEntry(RESULT, ms.ToArray()); zip.AddEntry(Utility.ResultFileName(ml.ToString() + ".pdf"), r1); zip.AddEntry(Utility.ResultFileName(mh.ToString()+ ".pdf"), r2); } zip.Save(stream); } }
private void InitializeDocument(String name) { output = OUT + name + ".pdf"; document = new Document(); copy = new PdfCopy(document, new FileStream(output, FileMode.Create)); copy.SetTagged(); document.Open(); }
public Combiner(string outputFilePath) { var outputStream = File.Create(outputFilePath); _document = new Document(); _pdfCopy = new PdfCopy(_document, outputStream); _document.Open(); }
protected internal PdfStructTreeController(PdfReader reader, PdfCopy writer){ if (!writer.IsTagged()) throw new BadPdfFormatException(MessageLocalization.GetComposedMessage("no.structtreeroot.found")); this.writer = writer; structureTreeRoot = writer.StructureTreeRoot; structureTreeRoot.Put(PdfName.PARENTTREE, new PdfDictionary(PdfName.STRUCTELEM)); SetReader(reader); }
/// <summary> /// Concatenates two or more PDF files into one file. /// </summary> /// <param name="inputFiles">A string array containing the names of the pdf files to concatenate</param> /// <param name="outputFile">Name of the concatenated file.</param> public void ConcatenatePDFFiles(String[] inputFiles, String outputFile) { if (inputFiles != null && inputFiles.Length > 0) { if (!String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile)) { var concatDocument = new iTextSharpText.Document(); var outputCopy = new iTextSharpPDF.PdfCopy(concatDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite)); concatDocument.Open(); try { for (int loop = 0; loop <= inputFiles.GetUpperBound(0); loop++) { var inputDocument = new iTextSharpPDF.PdfReader(inputFiles[loop]); for (int pageLoop = 1; pageLoop <= inputDocument.NumberOfPages; pageLoop++) { concatDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(pageLoop)); outputCopy.AddPage(outputCopy.GetImportedPage(inputDocument, pageLoop)); } inputDocument.Close(); outputCopy.FreeReader(inputDocument); inputDocument = null; } concatDocument.Close(); outputCopy.Close(); } catch { if (concatDocument != null && concatDocument.IsOpen()) { concatDocument.Close(); } if (outputCopy != null) { outputCopy.Close(); } if (File.Exists(outputFile)) { try { File.Delete(outputFile); } catch { } } throw; } } else { throw new ArgumentNullException("outputFile", exceptionArgumentNullOrEmptyString); } } else { throw new ArgumentNullException("inputFiles", exceptionArgumentNullOrEmptyString); } }
// --------------------------------------------------------------------------- /** * Creates a PDF file with director names. * @param pdf the PDF file to be used as a reader */ public byte[] CreatePdf(byte[] pdf) { byte[] tmpDoc = null; using ( MemoryStream ms = new MemoryStream() ) { using (Document tmp = new Document()) { PdfWriter writer = PdfWriter.GetInstance(tmp, ms); // step 3 tmp.Open(); // step 4 var SQL = @"SELECT name, given_name FROM film_director ORDER BY name, given_name"; using (var c = AdoDB.Provider.CreateConnection()) { c.ConnectionString = AdoDB.CS; using (DbCommand cmd = c.CreateCommand()) { cmd.CommandText = SQL; c.Open(); using (var r = cmd.ExecuteReader()) { while ( r.Read() ) { tmp.Add(CreateDirectorParagraph(writer, r)); } } } } } tmpDoc = ms.ToArray(); } jsContents = File.ReadAllText( Path.Combine(Utility.ResourceJavaScript, RESOURCE) ); List<byte[]> readers = new List<byte[]>() {tmpDoc, pdf}; using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { // step 2 using (PdfCopy copy = new PdfCopy(document, ms)) { // step 3 document.Open(); // step 4 copy.AddJavaScript(jsContents); for (int i = 0; i < readers.Count; ++i) { PdfReader reader = new PdfReader(readers[i]); int n = reader.NumberOfPages; for (int page = 0; page < n; ) { copy.AddPage(copy.GetImportedPage(reader, ++page)); } } } } return ms.ToArray(); } }
/** * Creates a new PDF based on the one in the reader * @param reader a reader with a PDF file * @throws IOException * @throws DocumentException */ private void ManipulateWithCopy(PdfReader reader) { int n = reader.NumberOfPages; Document document = new Document(); PdfCopy copy = new PdfCopy(document, new MemoryStream()); document.Open(); for (int i = 0; i < n; ) { copy.AddPage(copy.GetImportedPage(reader, ++i)); } document.Close(); }
private IList<PdfImportedPage> ExtractPagesFromFile(string sourcePdfPath) { IList<PdfImportedPage> pages = new List<PdfImportedPage>(); PdfReader reader = new PdfReader(sourcePdfPath); PdfCopy pdfCopyProvider = new PdfCopy(new Document(), new MemoryStream()); for (int i = 0; i < reader.NumberOfPages; i++) { pages.Add(pdfCopyProvider.GetImportedPage(reader, i + 1)); } return pages; }
public static byte[] MergeFiles(List<byte[]> sourceFiles) { Document document = new Document(); using (MemoryStream ms = new MemoryStream()) { PdfCopy copy = new PdfCopy(document, ms); document.Open(); int documentPageCounter = 0; // Iterate through all pdf documents for (int fileCounter = 0; fileCounter < sourceFiles.Count; fileCounter++) { // Create pdf reader PdfReader reader = new PdfReader(sourceFiles[fileCounter]); int numberOfPages = reader.NumberOfPages; // Iterate through all pages for (int currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++) { PdfImportedPage importedPage = copy.GetImportedPage(reader, currentPageIndex); //*************************************** // Uncomment and alter for watermarking. //*************************************** // //documentPageCounter++; //PdfCopy.PageStamp pageStamp = copy.CreatePageStamp(importedPage); // //// Write header //ColumnText.ShowTextAligned(pageStamp.GetOverContent(), Element.ALIGN_CENTER, // new Phrase("PDF Merged with me.AxeyWorks PDFMerge"), importedPage.Width / 2, importedPage.Height - 30, // importedPage.Width < importedPage.Height ? 0 : 1); // //// Write footer //ColumnText.ShowTextAligned(pageStamp.GetOverContent(), Element.ALIGN_CENTER, // new Phrase($"Page {documentPageCounter}"), importedPage.Width / 2, 30, // importedPage.Width < importedPage.Height ? 0 : 1); // //pageStamp.AlterContents(); copy.AddPage(importedPage); } copy.FreeReader(reader); reader.Close(); } document.Close(); return ms.GetBuffer(); } }
// --------------------------------------------------------------------------- /** * Creates a new PDF based on the one in the reader * @param reader a reader with a PDF file */ private byte[] ManipulateWithCopy(PdfReader reader) { using (MemoryStream ms = new MemoryStream()) { int n = reader.NumberOfPages; using (Document document = new Document()) { using (PdfCopy copy = new PdfCopy(document, ms)) { document.Open(); for (int i = 0; i < n;) { copy.AddPage(copy.GetImportedPage(reader, ++i)); } } } return ms.ToArray(); } }
private void StartThread() { List <String> filePaths = new List <string>(); // create one-page pdfs first iTextSharp.text.pdf.PdfReader reader = null; int currentPage = 1; int pageCount = 0; String filepath = textBox_file.Text; System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); reader = new iTextSharp.text.pdf.PdfReader(filepath); reader.RemoveUnusedObjects(); pageCount = reader.NumberOfPages; string ext = System.IO.Path.GetExtension(filepath); for (int i = 1; i <= pageCount; i++) { iTextSharp.text.pdf.PdfReader reader1 = new iTextSharp.text.pdf.PdfReader(filepath); string outfile = filepath.Replace((System.IO.Path.GetFileName(filepath)), (System.IO.Path.GetFileName(filepath).Replace(".pdf", "") + "_" + i.ToString()) + ext); reader1.RemoveUnusedObjects(); iTextSharp.text.Document doc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage)); iTextSharp.text.pdf.PdfCopy pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.Create)); doc.Open(); for (int j = 1; j <= 1; j++) { iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader1, currentPage); pdfCpy.AddPage(page); currentPage += 1; } doc.Close(); pdfCpy.Close(); reader1.Close(); reader.Close(); filePaths.Add(outfile); } DecomposeData decompose = new DecomposeData { filePathsPdf = filePaths, folder = textBox_destFolder.Text }; backgroundWorker1.RunWorkerAsync(decompose); label_status.Text = localization.GetValueForItem(LocalizedItem.TextSearchStarted).Replace("%i", filePaths.Count.ToString()); label_status.ForeColor = Color.Blue; }
private void freePDF() { if (avaPDF) { try { pdfReader.Dispose(); pdfDoc.Dispose(); pdfCopy.Dispose(); } catch { pdfReader = null; pdfDoc = null; pdfCopy = null; } } }
// --------------------------------------------------------------------------- /** * Fills out a data sheet, flattens it, and adds it to a combined PDF. * @param copy the PdfCopy instance (can also be PdfSmartCopy) */ public void AddDataSheets(PdfCopy copy) { IEnumerable<Movie> movies = PojoFactory.GetMovies(); // Loop over all the movies and fill out the data sheet foreach (Movie movie in movies) { PdfReader reader = new PdfReader(DATASHEET_PATH); using (var ms = new MemoryStream()) { using (PdfStamper stamper = new PdfStamper(reader, ms)) { Fill(stamper.AcroFields, movie); stamper.FormFlattening = true; } reader = new PdfReader(ms.ToArray()); copy.AddPage(copy.GetImportedPage(reader, 1)); } } }
public void Create(Album album, string outputPdfPath) { Document document = new Document(); PdfCopy pdfCopyProvider = new PdfCopy(document, new FileStream(outputPdfPath, FileMode.Create)); document.Open(); foreach (Page page in album.Pages) { AddTextForPage(pdfCopyProvider, page.Image, page.TextForPage); pdfCopyProvider.AddPage(page.Image); } document.Close(); }
public static void MergePdf() { using (var fs = new FileStream(@"C:\Projects\31g\trunk\Notes\misc\OccidentalMaps.pdf", FileMode.Create)) { var doc = new iTextSharp.text.Document(); var pdf = new iTextSharp.text.pdf.PdfCopy(doc, fs); doc.Open(); foreach (var file in Directory.GetFiles(@"C:\Projects\31g\trunk\Notes\misc\WestMaps")) { pdf.AddDocument(new iTextSharp.text.pdf.PdfReader(file)); } doc.Close(); } }
private void AddTextForPage(PdfCopy pdfCopyProvider, PdfImportedPage importedPage, TextForPage textForPage) { PdfCopy.PageStamp stamper = pdfCopyProvider.CreatePageStamp(importedPage); ColumnText.ShowTextAligned(stamper.GetOverContent(), Element.ALIGN_CENTER, new Phrase(textForPage.PageNubmer, new Font()), 820f, 15, 0); stamper.AlterContents(); AddParagraph(stamper, textForPage.Header, importedPage.Width / 2, importedPage.Height - 30, Element.ALIGN_CENTER, 1); AddParagraph(stamper, textForPage.Footer, importedPage.Width / 2, 30, Element.ALIGN_CENTER, 1); stamper.AlterContents(); }
/// <summary> /// Splits the PDF file /// </summary> /// <param name="filepath">The file to split</param> private void Split(string filepath) { this.statut.Text = "Début de la division"; this.statut.Refresh(); this.document.Text = Path.GetFileName(filepath); this.document.Refresh(); PdfReader reader = null; int currentPage = 1; int pageCount = 0; string dirPath = Path.GetDirectoryName(filepath); System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); reader = new iTextSharp.text.pdf.PdfReader(filepath); reader.RemoveUnusedObjects(); pageCount = reader.NumberOfPages; string ext = System.IO.Path.GetExtension(filepath); for (int i = 1; i <= pageCount; i++) { this.statut.Text = "En cours de division " + i + " / " + pageCount; this.statut.Refresh(); iTextSharp.text.pdf.PdfReader reader1 = new iTextSharp.text.pdf.PdfReader(filepath); string outfile = filepath.Replace(System.IO.Path.GetFileName(filepath), (System.IO.Path.GetFileName(filepath).Replace(FileExtension.PDF, string.Empty) + "_" + i.ToString()) + ext); outfile = outfile.Substring(0, dirPath.Length).Insert(dirPath.Length, string.Empty) + "\\" + Path.GetFileName(filepath).Replace(FileExtension.PDF, string.Empty) + "_" + i.ToString() + ext; reader1.RemoveUnusedObjects(); iTextSharp.text.Document doc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage)); iTextSharp.text.pdf.PdfCopy pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.OpenOrCreate)); doc.Open(); for (int j = 1; j <= 1; j++) { iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader1, currentPage); pdfCpy.AddPage(page); currentPage += 1; } this.progressBar1.PerformStep(); this.progressPages = this.progressPages + 1; this.label1.Text = this.progressPages + " / " + this.nbpages; this.label1.Refresh(); this.statut.Text = "Fin de la division " + i + " / " + pageCount; this.statut.Refresh(); doc.Close(); pdfCpy.Close(); reader1.Close(); reader.Close(); } }
public static void Merge(string file, string OutFile, ref SetupStationaryFields.addresscollection aic) { using (FileStream stream = new FileStream(OutFile, FileMode.Create)) { using (Document doc = new Document()) { using (PdfCopy pdf = new PdfCopy(doc, stream)) { doc.Open(); PdfReader reader = null; PdfImportedPage page = null; //fixed typo int ii = 0; int count = 0; foreach (SetupStationaryFields.addressitem ai in aic) { if ((!ai.ommitted)) { reader = new PdfReader(file); PdfReader.unethicalreading = true; count = reader.NumberOfPages; for (int i = 0; i <= reader.NumberOfPages - 1; i++) { page = pdf.GetImportedPage(reader, i + 1); pdf.AddPage(page); } pdf.FreeReader(reader); reader.Close(); ai.startpage = ((ii) * count) + 1; ai.endpage = (ii * count) + count; ii = ii + 1; } } } } stream.Close(); } }
protected override void Convert(ConversionOptions options) { if (m_sourceFiles != null) { if (m_sourceFiles.Count == 1 && !m_forceConversion) { this.OutputFile = m_sourceFiles[0]; } else { try { using (MemoryStream ms = new MemoryStream()) { using (Document doc = new Document(options.Orientation == PageOrientation.Portrait ? PageSize.LETTER : PageSize.LETTER_LANDSCAPE)) { PdfCopy copy = new PdfCopy(doc, ms); PdfReader reader; doc.Open(); int n; foreach (byte[] file in m_sourceFiles) { if (file != null) { reader = new PdfReader(file); n = reader.NumberOfPages; for (int page = 1; page <= n; page++) { copy.AddPage(copy.GetImportedPage(reader, page)); } copy.FreeReader(reader); } } } this.OutputFile = ms.ToArray(); } } catch (Exception ex) { throw new ConversionEngineException("Error when merging Pdf files.", null, "pdf", this, ex); } } } }
public static void BreakApart() { var reader = new iTextSharp.text.pdf.PdfReader(@"C:\Projects\31g\trunk\temp\20140208110036.pdf"); for (var i = 1; i < reader.NumberOfPages; i++) { var document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(i)); var pdfCopyProvider = new iTextSharp.text.pdf.PdfCopy(document, new System.IO.FileStream(string.Format(@"C:\Projects\31g\trunk\temp\pdf\20140208110036_{0}.pdf", i), System.IO.FileMode.Create)); document.Open(); var importedPage = pdfCopyProvider.GetImportedPage(reader, i); pdfCopyProvider.AddPage(importedPage); document.Close(); } reader.Close(); }
private void CombineMultiplePDFsCer(string[] fileNames, string outFile, bool deleteSource) { // step 1: creation of a document-object Document document = new Document(); //create newFileStream object which will be disposed at the end using (FileStream newFileStream = new FileStream(outFile, FileMode.Create)) { // step 2: we create a writer that listens to the document PdfCopy writer = new iTextSharp.text.pdf.PdfCopy(document, newFileStream); if (writer == null) { return; } // step 3: we open the document document.Open(); foreach (string fileName in fileNames) { // we create a reader for a certain document PdfReader reader = new PdfReader(fileName); reader.ConsolidateNamedDestinations(); // step 4: we add content for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } reader.Close(); if (deleteSource) { File.Delete(fileName); } } // step 5: we close the document and writer writer.Close(); document.Close(); }//disposes the newFileStream object }
// --------------------------------------------------------------------------- public override void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { // step 2 using (PdfCopy copy = new PdfCopy(document, ms)) { // step 3 document.Open(); // step 4 AddDataSheets(copy); } } zip.AddEntry(RESULT, ms.ToArray()); } zip.AddFile(DATASHEET_PATH, ""); zip.Save(stream); } }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF */ public byte[] ManipulatePdf(List<byte[]> src) { using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { // step 2 using (PdfCopy copy = new PdfCopy(document, ms)) { // step 3 document.Open(); // step 4 int page_offset = 0; // Create a list for the bookmarks List<Dictionary<String, Object>> bookmarks = new List<Dictionary<String, Object>>(); for (int i = 0; i < src.Count; i++) { PdfReader reader = new PdfReader(src[i]); // merge the bookmarks IList<Dictionary<String, Object>> tmp = SimpleBookmark.GetBookmark(reader); SimpleBookmark.ShiftPageNumbers(tmp, page_offset, null); foreach (var d in tmp) bookmarks.Add(d); // add the pages int n = reader.NumberOfPages; page_offset += n; for (int page = 0; page < n; ) { copy.AddPage(copy.GetImportedPage(reader, ++page)); } } // Add the merged bookmarks copy.Outlines = bookmarks; } } return ms.ToArray(); } }
public void CombineMultiplePDFs(string[] fileNames, string outFile) { // step 1: creation of a document-object Document document = new Document(); // step 2: we create a writer that listens to the document PdfCopy writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create)); if (writer == null) { return; } // step 3: we open the document document.Open(); foreach (string fileName in fileNames) { // we create a reader for a certain document PdfReader reader = new PdfReader(fileName); reader.ConsolidateNamedDestinations(); // step 4: we add content for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } reader.Close(); } // step 5: we close the document and writer writer.Close(); document.Close(); }
/// <summary> iTextSharp_PNG 无法正常进行展出操作 /// /// </summary> /// <param name="filepath"></param> /// <param name="outputPath"></param> /// <returns></returns> List <PPTPage> SplitePDF(string filepath, string outputPath) { List <PPTPage> pages = new List <PPTPage>(); iTextSharp.text.pdf.PdfReader reader = null; int currentPage = 1; int pageCount = 0; System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); reader = new iTextSharp.text.pdf.PdfReader(filepath); reader.RemoveUnusedObjects(); pageCount = reader.NumberOfPages; for (int i = 1; i <= pageCount;) { string outfile = System.IO.Path.Combine(outputPath, i + ".png"); iTextSharp.text.Document doc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage)); iTextSharp.text.pdf.PdfCopy pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.Create)); doc.Open(); for (int j = 1; j <= 1; j++) { iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader, currentPage); pdfCpy.SetFullCompression(); pdfCpy.AddPage(page); currentPage += 1; } Console.WriteLine("PDF TO IMAGES - {0}/{1}", ++i, pageCount); pages.Add(new PPTPage() { Cover = outfile }); pdfCpy.Flush(); doc.Close(); pdfCpy.Close(); reader.Close(); } return(pages); }
public void ExtractPages(string sourcePdfPath, string outputPdfPath, int[] extractThesePages) { PdfReader reader = null; Document sourceDocument = null; PdfCopy pdfCopyProvider = null; PdfImportedPage importedPage = null; try { // Intialize a new PdfReader instance with the // contents of the source Pdf file: reader = new PdfReader(sourcePdfPath); // For simplicity, I am assuming all the pages share the same size // and rotation as the first page: sourceDocument = new Document(reader.GetPageSizeWithRotation(extractThesePages[0])); // Initialize an instance of the PdfCopyClass with the source // document and an output file stream: pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create)); sourceDocument.Open(); // Walk the array and add the page copies to the output file: foreach (int pageNumber in extractThesePages) { importedPage = pdfCopyProvider.GetImportedPage(reader, pageNumber); pdfCopyProvider.AddPage(importedPage); } sourceDocument.Close(); reader.Close(); } catch (Exception ex) { throw ex; } }
public void ExtractPages(string sourcePdfPath, string outputPdfPath, int startPage, int endPage, string password = "") { PdfReader reader = null; Document sourceDocument = null; PdfCopy pdfCopyProvider = null; PdfImportedPage importedPage = null; try { // Intialize a new PdfReader instance with the contents of the source Pdf file: reader = new PdfReader(sourcePdfPath, Encoding.UTF8.GetBytes(password)); // For simplicity, I am assuming all the pages share the same size // and rotation as the first page: sourceDocument = new Document(reader.GetPageSizeWithRotation(startPage)); // Initialize an instance of the PdfCopyClass with the source // document and an output file stream: pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create)); sourceDocument.Open(); // Walk the specified range and add the page copies to the output file: for (int i = startPage; i <= endPage; i++) { importedPage = pdfCopyProvider.GetImportedPage(reader, i); pdfCopyProvider.AddPage(importedPage); } sourceDocument.Close(); reader.Close(); } catch (Exception ex) { throw ex; } }
private Byte[] CombineMultiplePDFs(List <Byte[]> fileNames) { Byte[] _Byte = null; Document document = new Document(); MemoryStream _PageAll = new MemoryStream(); PdfCopy writer = new iTextSharp.text.pdf.PdfCopy(document, _PageAll); if (writer == null) { return(_Byte); } // step 3: we open the document document.Open(); foreach (Byte[] fileName in fileNames.ToArray()) { // we create a reader for a certain document PdfReader reader = new PdfReader(fileName); reader.ConsolidateNamedDestinations(); // step 4: we add content for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } reader.Close(); } // step 5: we close the document and writer writer.Close(); document.Close(); return(_PageAll.ToArray()); }
public static void SplitePDF(string filepath) { iTextSharp.text.pdf.PdfReader reader = null; int currentPage = 1; int pageCount = 0; //string filepath_New = filepath + "\\PDFDestination\\"; System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); //byte[] arrayofPassword = encoding.GetBytes(ExistingFilePassword); reader = new iTextSharp.text.pdf.PdfReader(filepath); reader.RemoveUnusedObjects(); pageCount = reader.NumberOfPages; string ext = System.IO.Path.GetExtension(filepath); for (int i = 1; i <= pageCount; i++) { iTextSharp.text.pdf.PdfReader reader1 = new iTextSharp.text.pdf.PdfReader(filepath); string outfile = filepath.Replace((System.IO.Path.GetFileName(filepath)), (System.IO.Path.GetFileName(filepath).Replace(".pdf", "") + "_" + i.ToString()) + ext); reader1.RemoveUnusedObjects(); iTextSharp.text.Document doc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage)); iTextSharp.text.pdf.PdfCopy pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.Create)); pdfCpy.SetFullCompression(); doc.Open(); for (int j = 1; j <= 1; j++) { iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader1, currentPage); pdfCpy.AddPage(page); currentPage += 1; } doc.Close(); pdfCpy.Close(); reader1.Close(); reader.Close(); } }
virtual protected PdfArray BranchForm(Dictionary <string, object> level, PdfIndirectReference parent, String fname) { PdfArray arr = new PdfArray(); foreach (KeyValuePair <string, object> entry in level) { String name = entry.Key; Object obj = entry.Value; PdfIndirectReference ind = PdfIndirectReference; PdfDictionary dic = new PdfDictionary(); if (parent != null) { dic.Put(PdfName.PARENT, parent); } dic.Put(PdfName.T, new PdfString(name, PdfObject.TEXT_UNICODE)); String fname2 = fname + "." + name; int coidx = calculationOrder.IndexOf(fname2); if (coidx >= 0) { calculationOrderRefs[coidx] = ind; } if (obj is Dictionary <string, object> ) { dic.Put(PdfName.KIDS, BranchForm((Dictionary <string, object>)obj, ind, fname2)); arr.Add(ind); AddToBody(dic, ind); } else { List <object> list = (List <object>)obj; dic.MergeDifferent((PdfDictionary)list[0]); if (list.Count == 3) { dic.MergeDifferent((PdfDictionary)list[2]); int page = (int)list[1]; PdfDictionary pageDic = pageDics[page - 1]; PdfArray annots = pageDic.GetAsArray(PdfName.ANNOTS); if (annots == null) { annots = new PdfArray(); pageDic.Put(PdfName.ANNOTS, annots); } PdfNumber nn = (PdfNumber)dic.Get(iTextTag); dic.Remove(iTextTag); AdjustTabOrder(annots, ind, nn); } else { PdfDictionary field = (PdfDictionary)list[0]; PdfName v = field.GetAsName(PdfName.V); PdfArray kids = new PdfArray(); for (int k = 1; k < list.Count; k += 2) { int page = (int)list[k]; PdfDictionary pageDic = pageDics[page - 1]; PdfArray annots = pageDic.GetAsArray(PdfName.ANNOTS); if (annots == null) { annots = new PdfArray(); pageDic.Put(PdfName.ANNOTS, annots); } PdfDictionary widget = new PdfDictionary(); widget.Merge((PdfDictionary)list[k + 1]); widget.Put(PdfName.PARENT, ind); PdfNumber nn = (PdfNumber)widget.Get(iTextTag); widget.Remove(iTextTag); if (PdfCopy.IsCheckButton(field)) { PdfName _as = widget.GetAsName(PdfName.AS); if (v != null && _as != null) { widget.Put(PdfName.AS, v); } } else if (PdfCopy.IsRadioButton(field)) { PdfName _as = widget.GetAsName(PdfName.AS); if (v != null && _as != null && !_as.Equals(GetOffStateName(widget))) { if (!mergedRadioButtons.ContainsKey(list)) { mergedRadioButtons[list] = null; widget.Put(PdfName.AS, v); } else { widget.Put(PdfName.AS, GetOffStateName(widget)); } } } PdfIndirectReference wref = AddToBody(widget).IndirectReference; AdjustTabOrder(annots, wref, nn); kids.Add(wref); Propagate(widget, null, false); } dic.Put(PdfName.KIDS, kids); } arr.Add(ind); AddToBody(dic, ind); Propagate(dic, null, false); } } return(arr); }
internal PageStamp(PdfReader reader, PdfDictionary pageN, PdfCopy cstp) { _pageN = pageN; _reader = reader; _cstp = cstp; }
internal PageStamp(PdfReader reader, PdfDictionary pageN, PdfCopy cstp) { this.pageN = pageN; this.reader = reader; this.cstp = cstp; }
private Boolean lockPDF(String r_password, String w_password) { string rp = null, wp = null; //////////////////////////////////////////////////// // PDF施錠 //////////////////////////////////////////////////// if (avaPDF) { // 一時ファイル取得 String tmpFilePath = Path.GetTempFileName(); // パスワードなしで読み込み可能かチェック try { pdfReader = new PdfReader(dataGridView1.Rows[0].Cells[3].Value.ToString()); } catch { label2.Text = WindowsFormsApplication1.Properties.Resources.pdf1; // "This document has been password-protected."; return(false); } // オーナーパスワードが掛っているかチェック if (pdfReader.IsEncrypted()) { label2.Text = WindowsFormsApplication1.Properties.Resources.pdf2; // "This document has been password-protected."; return(false); } pdfDoc = new iTextSharp.text.Document(pdfReader.GetPageSize(1)); os = new FileStream(tmpFilePath, FileMode.OpenOrCreate); pdfCopy = new PdfCopy(pdfDoc, os); // 出力ファイルにパスワード設定 // rp:ユーザーパスワード // wp:オーナーパスワード(空の場合はユーザーパスワードと同じ値を設定) pdfCopy.Open(); if (r_password.Length == 0) { rp = null; } else { rp = r_password; } if (w_password.Length == 0) { wp = r_password; pdfCopy.SetEncryption( PdfCopy.STRENGTH128BITS, rp, wp, PdfCopy.markAll); } else { wp = w_password; // AllowPrinting 印刷 // AllowCopy 内容のコピーと抽出 // AllowModifyContents 文書の変更 // AllowModifyAnnotations 注釈の入力 // AllowFillIn フォーム・フィールドの入力と署名 // AllowScreenReaders アクセシビリティのための内容抽出 // AllowAssembly 文書アセンブリ pdfCopy.SetEncryption( PdfCopy.STRENGTH128BITS, rp, wp, PdfCopy.AllowScreenReaders | PdfCopy.AllowPrinting); } try { // 出力ファイルDocumentを開く pdfDoc.Open(); // アップロードPDFファイルの内容を出力ファイルに書き込む pdfCopy.AddDocument(pdfReader); // 出力ファイルDocumentを閉じる pdfDoc.Close(); pdfCopy.Close(); os.Close(); pdfReader.Close(); // オリジナルファイルと一時ファイルを置き換える File.Delete(dataGridView1.Rows[0].Cells[3].Value.ToString()); File.Move(tmpFilePath, dataGridView1.Rows[0].Cells[3].Value.ToString()); } catch (Exception eX) { label2.Text = WindowsFormsApplication1.Properties.Resources.error1 + eX.Message; // "Saving failed." + eX.Message; return(false); } } return(true); }
/// <summary> /// Extracts a range of pages from a PDF file, /// and writes them to a new file. /// </summary> /// <param name="inputFile">The PDF to extract pages from.</param> /// <param name="outputFile">The new file to write the extracted pages to.</param> /// <param name="firstPage">The first page to extract.</param> /// <param name="lastPage">The last page to extract.</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <remarks><see cref="FileStream"/> constructor exceptions may also be thrown.</remarks> public void ExtractPDFPages(String inputFile, String outputFile, int firstPage, int lastPage) { if (!String.IsNullOrEmpty(inputFile) && !String.IsNullOrWhiteSpace(inputFile) && !String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile) && firstPage > 0 && lastPage > 0 && lastPage >= firstPage) { var inputDocument = new iTextSharpPDF.PdfReader(inputFile); try { // Page numbers specified must not be greater // than the number of pages in the document if (firstPage <= inputDocument.NumberOfPages && lastPage <= inputDocument.NumberOfPages) { iTextSharpText.Document extractOutputDocument = null; iTextSharpPDF.PdfCopy extractOutputFile = null; try { extractOutputDocument = new iTextSharpText.Document(); extractOutputFile = new iTextSharpPDF.PdfCopy(extractOutputDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite)); extractOutputDocument.Open(); for (int loop = firstPage; loop <= lastPage; loop++) { extractOutputDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(loop)); extractOutputFile.AddPage(extractOutputFile.GetImportedPage(inputDocument, loop)); } } finally { if (extractOutputDocument != null && extractOutputDocument.IsOpen()) { extractOutputDocument.Close(); } if (extractOutputFile != null) { extractOutputFile.Close(); extractOutputFile.FreeReader(inputDocument); } } } else { if (firstPage > inputDocument.NumberOfPages) { throw new ArgumentOutOfRangeException("firstPage", String.Format(exceptionParameterCannotBeGreaterThan, "firstPage", "the number of pages in the document.")); } throw new ArgumentOutOfRangeException("lastPage", String.Format(exceptionParameterCannotBeGreaterThan, "firstPage", "the number of pages in the document.")); } } catch { try { File.Delete(outputFile); } catch { } throw; } finally { if (inputDocument != null) { inputDocument.Close(); } inputDocument = null; } } else { if (String.IsNullOrEmpty(inputFile) || String.IsNullOrWhiteSpace(inputFile)) { throw new ArgumentNullException("inputFile", exceptionArgumentNullOrEmptyString); } if (String.IsNullOrEmpty(outputFile) || String.IsNullOrWhiteSpace(outputFile)) { throw new ArgumentNullException("outputFile", exceptionArgumentNullOrEmptyString); } if (firstPage < 1) { throw new ArgumentOutOfRangeException("firstPage", exceptionArgumentZeroOrNegative); } if (lastPage < 1) { throw new ArgumentOutOfRangeException("lastPage", exceptionArgumentZeroOrNegative); } if (lastPage < firstPage) { throw new ArgumentOutOfRangeException("lastPage", String.Format(exceptionParameterCannotBeLessThan, "lastPage", "firstPage")); } } }
/// <summary> /// Takes pages from two pdf files, and produces an output file /// whose odd pages are the contents of the first, and /// even pages are the contents of the second. Useful for /// merging front/back output from single sided scanners. /// </summary> /// <param name="oddPageFile">The file supplying odd numbered pages</param> /// <param name="evenPageFile">The file supplying even numbered pages</param> /// <param name="outputFile">The output file containing the merged pages</param> /// <param name="skipExtraPages">Set to true to skip any extra pages if /// one file is longer than the other</param> public void EvenOddMerge(String oddPageFile, String evenPageFile, String outputFile, bool skipExtraPages) { if (!String.IsNullOrEmpty(oddPageFile) && !String.IsNullOrWhiteSpace(oddPageFile) && !String.IsNullOrEmpty(evenPageFile) && !String.IsNullOrWhiteSpace(evenPageFile) && !String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile)) { var oddPageDocument = new iTextSharpPDF.PdfReader(oddPageFile); var evenPageDocument = new iTextSharpPDF.PdfReader(evenPageFile); try { iTextSharpText.Document mergedOutputDocument = null; iTextSharpPDF.PdfCopy mergedOutputFile = null; int lastPage = 0; switch (skipExtraPages) { case (false): lastPage = oddPageDocument.NumberOfPages; if (evenPageDocument.NumberOfPages > oddPageDocument.NumberOfPages) { lastPage = evenPageDocument.NumberOfPages; } else { lastPage = oddPageDocument.NumberOfPages; } break; case (true): if (evenPageDocument.NumberOfPages < oddPageDocument.NumberOfPages) { lastPage = evenPageDocument.NumberOfPages; } else { lastPage = oddPageDocument.NumberOfPages; } break; } try { mergedOutputDocument = new iTextSharpText.Document(); mergedOutputFile = new iTextSharpPDF.PdfCopy(mergedOutputDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite)); mergedOutputDocument.Open(); for (int loop = 1; loop <= lastPage; loop++) { // Extract and merge odd page if (loop <= oddPageDocument.NumberOfPages) { mergedOutputDocument.SetPageSize(oddPageDocument.GetPageSizeWithRotation(loop)); mergedOutputFile.AddPage(mergedOutputFile.GetImportedPage(oddPageDocument, loop)); } // Extract and merge even page if (loop <= evenPageDocument.NumberOfPages) { mergedOutputDocument.SetPageSize(evenPageDocument.GetPageSizeWithRotation(loop)); mergedOutputFile.AddPage(mergedOutputFile.GetImportedPage(evenPageDocument, loop)); } } } finally { if (mergedOutputDocument != null && mergedOutputDocument.IsOpen()) { mergedOutputDocument.Close(); } if (mergedOutputFile != null) { mergedOutputFile.Close(); mergedOutputFile.FreeReader(oddPageDocument); mergedOutputFile.FreeReader(evenPageDocument); } } } catch { try { File.Delete(outputFile); } catch { } throw; } finally { try { if (oddPageDocument != null) { oddPageDocument.Close(); } oddPageDocument = null; } catch { } try { if (evenPageDocument != null) { evenPageDocument.Close(); } evenPageDocument = null; } catch { } } } else { if (String.IsNullOrEmpty(oddPageFile) || String.IsNullOrWhiteSpace(oddPageFile)) { throw new ArgumentNullException("oddPageFile", exceptionArgumentNullOrEmptyString); } if (String.IsNullOrEmpty(evenPageFile) || String.IsNullOrWhiteSpace(evenPageFile)) { throw new ArgumentNullException("evenPageFile", exceptionArgumentNullOrEmptyString); } if (String.IsNullOrEmpty(outputFile) || String.IsNullOrWhiteSpace(outputFile)) { throw new ArgumentNullException("outputFile", exceptionArgumentNullOrEmptyString); } } }
private Boolean unlockPDF(String r_password, String w_password) { Boolean NOPASS = true; //////////////////////////////////////////////////// // PDF解錠 //////////////////////////////////////////////////// if (avaPDF) { // 一時ファイル取得 String tmpFilePath = Path.GetTempFileName(); Boolean isRP = false; Boolean isWP = false; // パスワードなしで読み込めるかチェック try { pdfReader = new PdfReader(dataGridView1.Rows[0].Cells[3].Value.ToString()); isRP = false; // ユーザーパスワードなし // オーナーパスワードが掛っているかチェック isWP = (pdfReader.IsEncrypted()) ? true : false; NOPASS = !(isRP || isWP); pdfReader.Close(); pdfReader.Dispose(); } catch { isRP = true; NOPASS = false; } if (NOPASS) { // パスワードがかかっていない label2.Text = WindowsFormsApplication1.Properties.Resources.pdf2; //"This document is not applied password."; pdfReader.Close(); pdfReader.Dispose(); return(false); } if (isRP && (r_password.Length == 0)) { // ユーザーパスワードが掛っているが、入力されていない label2.Text = WindowsFormsApplication1.Properties.Resources.pdf3; // "This document has been user password-protected."; return(false); } if (isWP && (w_password.Length == 0)) { // オーナーパスワードが掛っているが、入力されていない label2.Text = WindowsFormsApplication1.Properties.Resources.pdf4; //"This document has been owner password-protected."; return(false); } String rp = (r_password.Length == 0) ? null : r_password; String wp = (w_password.Length == 0) ? r_password : w_password; try { pdfReader = new PdfReader(dataGridView1.Rows[0].Cells[3].Value.ToString(), (byte[])System.Text.Encoding.ASCII.GetBytes(wp)); } catch { label2.Text = WindowsFormsApplication1.Properties.Resources.message2; // "Password is incorrect."; return(false); } try { pdfDoc = new iTextSharp.text.Document(pdfReader.GetPageSize(1)); os = new FileStream(tmpFilePath, FileMode.OpenOrCreate); pdfCopy = new PdfCopy(pdfDoc, os); pdfCopy.Open(); pdfDoc.Open(); pdfCopy.AddDocument(pdfReader); pdfDoc.Close(); pdfCopy.Close(); pdfReader.Close(); pdfReader.Dispose(); // オリジナルファイルと一時ファイルを置き換える System.IO.File.Copy(tmpFilePath, dataGridView1.Rows[0].Cells[3].Value.ToString(), true); System.IO.File.Delete(tmpFilePath); } catch (Exception eX) { label2.Text = WindowsFormsApplication1.Properties.Resources.error1 + eX.Message; // "Saving failed." + eX.Message; return(false); } } return(true); }
/// <summary> /// /// </summary> /// <param name="inputFile">The PDF file to split</param> /// <param name="splitStartPages"></param> public void SplitPDF(String inputFile, SortedList <int, String> splitStartPages) { if (!String.IsNullOrEmpty(inputFile) && !String.IsNullOrWhiteSpace(inputFile) && splitStartPages != null && splitStartPages.Count >= 2) { var inputDocument = new iTextSharpPDF.PdfReader(inputFile); // First split must begin with page 1 // Last split must not be higher than last page if (splitStartPages.Keys[0] == 1 && splitStartPages.Keys[splitStartPages.Count - 1] <= inputDocument.NumberOfPages) { int currentPage = 1; int firstPageOfSplit; int lastPageOfSplit; try { for (int splitPoint = 0; splitPoint <= (splitStartPages.Count - 1); splitPoint++) { firstPageOfSplit = currentPage; if (splitPoint < (splitStartPages.Count - 1)) { lastPageOfSplit = splitStartPages.Keys[splitPoint + 1] - 1; } else { lastPageOfSplit = inputDocument.NumberOfPages; } iTextSharpText.Document splitDocument = null; iTextSharpPDF.PdfCopy splitOutputFile = null; try { splitDocument = new iTextSharpText.Document(); splitOutputFile = new iTextSharpPDF.PdfCopy(splitDocument, new FileStream(splitStartPages.Values[splitPoint], FileMode.Create, FileAccess.ReadWrite)); splitDocument.Open(); for (int outputPage = firstPageOfSplit; outputPage <= lastPageOfSplit; outputPage++) { splitDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(currentPage)); splitOutputFile.AddPage(splitOutputFile.GetImportedPage(inputDocument, currentPage)); currentPage++; } } finally { if (splitDocument != null && splitDocument.IsOpen()) { splitDocument.Close(); } if (splitOutputFile != null) { splitOutputFile.Close(); splitOutputFile.FreeReader(inputDocument); } splitDocument = null; splitOutputFile = null; } } } catch { // Cleanup any files that may have // been written foreach (KeyValuePair <int, String> split in splitStartPages) { try { File.Delete(split.Value); } catch { } } throw; } finally { if (inputDocument != null) { inputDocument.Close(); } } } else { if (splitStartPages.Keys[splitStartPages.Count - 1] > inputDocument.NumberOfPages) { throw new ArgumentOutOfRangeException("splitStartPages", String.Format("Final page number must be less than the number of pages ({0}). Passed value is {1}.", inputDocument.NumberOfPages, splitStartPages.Keys[splitStartPages.Count - 1])); } throw new ArgumentOutOfRangeException("splitStartPages", "First page number must be 1."); } } else { if (inputFile == null) { throw new ArgumentNullException("inputFile", exceptionArgumentNullOrEmptyString); } if (splitStartPages == null) { throw new ArgumentNullException("splitStartPages", exceptionArgumentNullOrEmptyString); } throw new ArgumentOutOfRangeException("splitStartPages", "Must contain at least two KeyValue pairs."); } }
static void test01(string file) { var db = RedisWrite.Db; if (!File.Exists(file)) { return; } var reader = new iTextSharpPdf.PdfReader(file); reader.RemoveUnusedObjects(); long fileSize = reader.FileLength; int currentPage = 1; var readerCopy = new iTextSharpPdf.PdfReader(file); readerCopy.RemoveUnusedObjects(); readerCopy.RemoveAnnotations(); readerCopy.RemoveFields(); readerCopy.RemoveUsageRights(); string CreationDate = ""; foreach (KeyValuePair <string, string> KV in readerCopy.Info) { if (KV.Key == "CreationDate") { CreationDate = KV.Value; } //readerCopy.Info.Remove(KV.Key); } //int headerSize = readerCopy.Metadata.Length; //string mt = Encoding.UTF8.GetString(readerCopy.Metadata); int max = reader.NumberOfPages; if (max > 5) { max = 2; } string key = DocumentStatic.buildId(max, fileSize); var obj = new Dictionary <string, object>() { { "id", long.Parse(key) }, { "file_name", Path.GetFileNameWithoutExtension(file) }, { "file_type", "pdf" }, { "file_size", fileSize }, { "file_created", CreationDate }, { "page", max } }; string jsonInfo = JsonConvert.SerializeObject(obj); var bufInfo = ASCIIEncoding.UTF8.GetBytes(jsonInfo); var lsEntry = new List <NameValueEntry>() { new NameValueEntry(0, LZ4.LZ4Codec.Encode(bufInfo, 0, bufInfo.Length)) }; for (int i = 1; i <= max; i++) { ////using (FileStream fs = new FileStream(@"C:\temp\" + i + "-.pdf", FileMode.Create, FileAccess.Write, FileShare.None)) ////{ //// using (var d = new iTextSharpText.Document()) //// { //// using (var w = new iTextSharpPdf.PdfCopy(d, fs)) //// { //// d.Open(); //// w.AddPage(w.GetImportedPage(reader, i)); //// d.Close(); //// } //// } ////} using (var ms = new MemoryStream()) { var docCopy = new iTextSharpText.Document(reader.GetPageSizeWithRotation(currentPage)); //var pdfCopy = new iTextSharpPdf.PdfCopy(docCopy, new FileStream(@"C:\temp\" + i + "-.pdf", FileMode.Create)); var pdfCopy = new iTextSharpPdf.PdfCopy(docCopy, ms); docCopy.Open(); var page = pdfCopy.GetImportedPage(readerCopy, currentPage); pdfCopy.SetFullCompression(); pdfCopy.AddPage(page); currentPage += 1; //long len = ms.Length; docCopy.Close(); pdfCopy.Close(); //m_app.RedisUpdate(key, i.ToString(), ms.ToArray()); lsEntry.Add(new NameValueEntry(i, ms.ToArray())); } } readerCopy.Close(); reader.Close(); string did = db.StreamAdd("BUF", lsEntry.ToArray(), key + "-0"); }
static void Main(string[] args) { // Changes \ to / in the path string string oldstr = @"\"; string newstr = @"/"; string pdf_path_original = string.Empty; // Tells the file path Console.WriteLine("FILE PATH: "); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("ファイル パス: "); pdf_path_original = Console.ReadLine(); string pdf_path = pdf_path_original.Replace(oldstr, newstr); // Tells the file name Console.WriteLine(".pdf`s Name: "); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("ファイルの名前は: "); string pdf_file_name = Console.ReadLine(); string path_n_name = pdf_path + "/" + pdf_file_name + ".pdf"; // Tells the file alignment Console.WriteLine("Text alignment: "); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("テキスト配置: "); Console.WriteLine("1: Left (左), and Right (右), or 2: Middle (真ん中)"); string caseSwitch = Console.ReadLine(); Console.WriteLine(); // Tells the file start page and end page Console.WriteLine(".pdf`s Initial Page "); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("最初のページは: "); string startpage_string = Console.ReadLine(); int startpage = Int32.Parse(startpage_string); Console.WriteLine(".pdf`s Last Page "); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("最後のページは: "); string endpage_string = Console.ReadLine(); int endpage = Int32.Parse(endpage_string); // Creates blank pdf files for (int i = startpage; i <= endpage; i++) { string convi = i.ToString(); // Creates a temp folder for the pdf files System.IO.Directory.CreateDirectory(pdf_path + "/" + "temp"); System.IO.FileStream pdf_creator = new System.IO.FileStream(pdf_path + "/" + "temp" + "/" + convi + ".pdf", System.IO.FileMode.Create); pdf_creator.Close(); } // Tells the attributes from the new pdf files, and the original pdf source iTextSharp.text.pdf.PdfReader reader = null; iTextSharp.text.Document sourceDocument = null; iTextSharp.text.pdf.PdfCopy pdfCopyProvider = null; iTextSharp.text.pdf.PdfImportedPage importedPage = null; reader = new iTextSharp.text.pdf.PdfReader(path_n_name); sourceDocument = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(startpage)); sourceDocument.Open(); // Creates a .docx to receive the pdf's text Spire.Doc.Document word_doc = new Spire.Doc.Document(); // Word doc formatting Spire.Doc.Section word_doc_section = word_doc.AddSection(); Spire.Doc.Documents.Paragraph word_doc_paragraph = word_doc_section.AddParagraph(); Spire.Doc.Documents.Paragraph word_doc_paragraph_page = word_doc_section.AddParagraph(); // Update those blank pdf files, inserting the copied pages into it try { for (int i = startpage; i <= endpage; i++) { string convi = i.ToString(); pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(pdf_path + "/" + "temp" + "/" + convi + ".pdf", System.IO.FileMode.Append)); sourceDocument.Open(); importedPage = pdfCopyProvider.GetImportedPage(reader, i); pdfCopyProvider.AddPage(importedPage); } sourceDocument.Close(); reader.Close(); } // ERROR catch (Exception ex) { Console.WriteLine("Error! "); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("エラー ! "); throw ex; } // Collects the text without furigana from the listed pdf files switch (caseSwitch) { // case 1 reffers to the left and right alignments of the pdf text case "1": Console.WriteLine(); for (int i = startpage; i <= endpage; i++) { // the following refers to the int counter of pages being converted into string string convi = i.ToString(); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("今のページ: " + convi); Console.WriteLine("Current Page: " + convi); // the following refers to the bitmiracle api pdf to get the texts using (BitMiracle.Docotic.Pdf.PdfDocument pdf_1 = new BitMiracle.Docotic.Pdf.PdfDocument(pdf_path + "/" + "temp" + "/" + convi + ".pdf")) { BitMiracle.Docotic.Pdf.PdfPage page = pdf_1.Pages[0]; foreach (PdfTextData data in page.GetWords()) { if (data.FontSize > 6 && data.Position.X < 600) { string text = data.Text; text.TrimEnd(); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine(text); //word_builder.Writeln(text); word_doc_paragraph.AppendText(text); } } foreach (PdfTextData data in page.GetWords()) { if (data.FontSize > 6 && data.Position.X > 600) { string text = data.Text; text.TrimEnd(); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine(text); word_doc_paragraph.AppendText(text); } } } // the following lines reffers to the space between pages of the pdf text Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); // the followin reffers to the extra lines on word text word_doc_paragraph.AppendText(" "); word_doc_paragraph.AppendText("CURRENT PAGE: " + convi); word_doc_paragraph = word_doc_section.AddParagraph(); word_doc.Sections[0].Paragraphs[i].AppendBreak(BreakType.PageBreak); } break; // case 2 reffers to the alignment of the pdf text that is centralized case "2": Console.WriteLine(); for (int i = startpage; i <= endpage; i++) { // the following refers to the int counter of pages being converted into string string convi = i.ToString(); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("今のページ: " + convi); Console.WriteLine("Current Page: " + convi); // the following refers to the bitmiracle api pdf to get the texts using (BitMiracle.Docotic.Pdf.PdfDocument pdf_1 = new BitMiracle.Docotic.Pdf.PdfDocument(pdf_path + "/" + "temp" + "/" + convi + ".pdf")) { BitMiracle.Docotic.Pdf.PdfPage page = pdf_1.Pages[0]; foreach (PdfTextData data in page.GetWords()) { if (data.FontSize > 6) { string text = data.Text; text.TrimEnd(); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine(text); word_doc_paragraph.AppendText(text); } } } Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); word_doc_paragraph.AppendText(" "); word_doc_paragraph.AppendText("CURRENT PAGE: " + convi); word_doc_paragraph = word_doc_section.AddParagraph(); word_doc.Sections[0].Paragraphs[i].AppendBreak(BreakType.PageBreak); } break; default: Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("error! (エラー)"); Console.ReadKey(); break; } // The following refers to creating a .docx file, opening up the file and deleting the temp folder word_doc.SaveToFile(pdf_path + "/" + pdf_file_name + ".docx", FileFormat.Docx); System.IO.Directory.Delete(pdf_path + "/" + "temp", true); try { System.Diagnostics.Process.Start(pdf_path + "/" + pdf_file_name + ".docx"); } catch { Console.WriteLine("Error! "); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("エラー ! "); } }
/// <summary> /// Concatenates two or more PDF files into one file. /// </summary> /// <param name="inputFiles">A string array containing the names of the pdf files to concatenate</param> /// <param name="outputFile">Name of the concatenated file.</param> public void ConcatenatePDFFiles(String[] inputFiles, String outputFile) { if (inputFiles != null && inputFiles.Length > 0) { if (!String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile)) { var concatDocument = new iTextSharpText.Document(); var outputCopy = new iTextSharpPDF.PdfCopy(concatDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite)); concatDocument.Open(); try { for (int loop = 0; loop <= inputFiles.GetUpperBound(0); loop++) { var inputDocument = new iTextSharpPDF.PdfReader(inputFiles[loop]); for (int pageLoop = 1; pageLoop <= inputDocument.NumberOfPages; pageLoop++) { concatDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(pageLoop)); outputCopy.AddPage(outputCopy.GetImportedPage(inputDocument, pageLoop)); } inputDocument.Close(); outputCopy.FreeReader(inputDocument); inputDocument = null; } concatDocument.Close(); outputCopy.Close(); } catch { if (concatDocument != null && concatDocument.IsOpen()) concatDocument.Close(); if (outputCopy != null) outputCopy.Close(); if (File.Exists(outputFile)) { try { File.Delete(outputFile); } catch { } } throw; } } else { throw new ArgumentNullException("outputFile", exceptionArgumentNullOrEmptyString); } } else { throw new ArgumentNullException("inputFiles", exceptionArgumentNullOrEmptyString); } }