/// <summary> /// Reads a PDF file and extracts all text-searchable content from it. /// </summary> /// <param name="file">The file to extract text from.</param> /// <returns>The text from the PDF file</returns> public static string ReadFile(string file) { if (string.IsNullOrEmpty(file)) throw new ArgumentNullException("file", "file cannot be null or empty"); FileInfo info = new FileInfo(file); if (!info.Exists) throw new FileNotFoundException("file must exist"); if (!info.Extension.Equals(".pdf", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException("File must have a .pdf extension"); System.Text.StringBuilder builder = new System.Text.StringBuilder(); iTextSharp.text.pdf.PdfReader reader = null; try { reader = new iTextSharp.text.pdf.PdfReader(info.FullName); for (int i = 1; i <= reader.NumberOfPages; i++) { builder.Append(ExtractTextFromPDFBytes(reader.GetPageContent(i))); builder.Append(' '); } } catch (Exception) { } finally { if (reader != null) reader.Close(); } return builder.ToString(); }
//srcで指定されたPDFファイルをページ毎に分割し、destで指定されたパスに保存する。 //保存ファイル名は「ファイル名-ページ番号.pdf」とする。 //分割したページ数を返す。 public List<string> Run(string src, string dest) { // srcで渡されたファイルが存在するか? if (!File.Exists(src)) { throw new FileNotFoundException(); } // destで渡されたフォルダが存在するか? if (!Directory.Exists(dest)) { throw new DirectoryNotFoundException(); } var reader = new iTextSharp.text.pdf.PdfReader(src); string file_name = Path.GetFileNameWithoutExtension(src); int digit = reader.NumberOfPages.ToString().Length; var app_name = new MainForm(); // 一時フォルダにpdfを作成してdestにコピー。 // その際上書き確認を行う。 System.IO.DirectoryInfo del = new System.IO.DirectoryInfo(Path.GetTempPath() + "\\" + app_name.Text); if (del.Exists) del.Delete(true); System.IO.DirectoryInfo tmp = new System.IO.DirectoryInfo(Path.GetTempPath() + "\\" + app_name.Text); tmp.Create(); for (int i = 1; i <= reader.NumberOfPages; i++) { var doc = new iTextSharp.text.Document(); var dest_tmp = String.Format(@"{{0}}\{{1}}-{{2:D{0}}}.pdf", digit); var dest_name = String.Format(dest_tmp, tmp, file_name, i); var copy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(dest_name, FileMode.Create)); doc.Open(); copy.AddPage(copy.GetImportedPage(reader, i)); doc.Close(); } // コピーしたファイルを監視する Ret.list.Clear(); var watcher = new System.IO.FileSystemWatcher(); watcher.Path = dest; watcher.Filter = "*.pdf"; watcher.Changed += new FileSystemEventHandler(changed); watcher.Created += new FileSystemEventHandler(changed); watcher.EnableRaisingEvents = true; FileSystem.CopyDirectory(tmp.ToString(), dest, UIOption.AllDialogs); watcher.EnableRaisingEvents = false; watcher.Dispose(); watcher = null; tmp.Delete(true); reader.Close(); return Ret.list; }
public static string[] ListEmbeddedFileNames(string pdfFileName) { string[] fileNames = new string[0]; var reader = new iTextSharp.text.pdf.PdfReader(pdfFileName); if (reader != null) { var root = reader.Catalog; if (root != null) { var names = root.GetAsDict(iTextSharp.text.pdf.PdfName.NAMES); if (names != null) { var embeddedFiles = names.GetAsDict(iTextSharp.text.pdf.PdfName.EMBEDDEDFILES); if (embeddedFiles != null) { var namesArray = embeddedFiles.GetAsArray(iTextSharp.text.pdf.PdfName.NAMES); if (namesArray != null) { int n = namesArray.Size / 2; // I don't understand why I have to divide by 2 fileNames = new string[n]; for (int i = 0; i < n; i++) { fileNames[i] = namesArray[2 * i].ToString(); } } } } } reader.Close(); } return(fileNames); }
private void createCombinedPdf_iTextSharp(List <string> InFiles, string OutFile) { try { using (var stream = new System.IO.FileStream(OutFile, System.IO.FileMode.Create)) using (var doc = new iTextSharp.text.Document()) using (var pdf = new iTextSharp.text.pdf.PdfCopy(doc, stream)) { doc.Open(); iTextSharp.text.pdf.PdfReader reader = null; iTextSharp.text.pdf.PdfImportedPage page = null; //fixed typo InFiles.ForEach(file => { reader = new iTextSharp.text.pdf.PdfReader(file); for (int i = 0; i < reader.NumberOfPages; i++) { page = pdf.GetImportedPage(reader, i + 1); pdf.AddPage(page); } pdf.FreeReader(reader); reader.Close(); System.IO.File.Delete(file); }); } } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } }
// ==================================================================================================== // ==================================================================================================== #region MÉTODOS PÚBLICOS RECLAMACIONES // ==================================================================================================== public void GenerarReclamación(Centros centro, Conductor conductor, DateTime fecha, string ruta) { // Creamos el lector del documento. string rutaPlantilla = Utils.CombinarCarpetas(App.RutaInicial, $"/Plantillas/Reclamacion.pdf"); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(rutaPlantilla); // Creamos el 'modificador' del documento. FileStream fs = new FileStream(ruta, FileMode.Create); iTextSharp.text.pdf.PdfStamper stamper = new iTextSharp.text.pdf.PdfStamper(reader, fs); // Extraemos los campos del documento. iTextSharp.text.pdf.AcroFields campos = stamper.AcroFields; // Asignamos los campos campos.SetField("Centro", centro.ToString().ToUpper()); campos.SetField("Trabajador", $"{conductor.Apellidos}, {conductor.Nombre} ({conductor.Id:000})"); campos.SetField("FechaCabecera", $"{fecha:MMMM - yyyy}".ToUpper()); campos.SetField("NumeroReclamacion", $"Nº Reclamación: {fecha:yyyyMM}{conductor.Id:000}/01"); campos.SetField("FechaFirma", $"{DateTime.Today:dd - MM - yyyy}"); // Cerramos los elementos abiertos stamper.Close(); fs.Close(); reader.Close(); }
private static void MergeFiles(string destinationFile, string ExportPath) { #region new code using (FileStream stream = new FileStream(destinationFile, FileMode.Create)) { iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4); iTextSharp.text.pdf.PdfCopy pdf = new iTextSharp.text.pdf.PdfCopy(pdfDoc, stream); pdfDoc.Open(); var files = Directory.GetFiles(ExportPath); int i = 1; foreach (string file in files) { // MemoryStream content= new MemoryStream( var reader = new iTextSharp.text.pdf.PdfReader(file); pdf.AddDocument(reader); i++; reader.Close(); } if (pdfDoc != null) { pdfDoc.Close(); } } #endregion }
private System.IO.MemoryStream addBlankPages(System.IO.MemoryStream orig_stream, int num_to_add = 1) { if (num_to_add == 0) { return(orig_stream); } System.IO.MemoryStream dest_stream = null; try { dest_stream = new System.IO.MemoryStream(); var reader = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray()); var stamper = new iTextSharp.text.pdf.PdfStamper(reader, dest_stream); for (var i = 1; i <= num_to_add; i++) { stamper.InsertPage(reader.NumberOfPages + 1, reader.GetPageSizeWithRotation(1)); } stamper.Close(); reader.Close(); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } return(dest_stream); }
private void Open_Button_Click(object sender, EventArgs e) { String Temp; using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "PDF files|*.pdf", ValidateNames = true, Multiselect = false }) { if (ofd.ShowDialog() == DialogResult.OK) { try { iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(ofd.FileName); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= reader.NumberOfPages; i++) { sb.Append(PdfTextExtractor.GetTextFromPage(reader, i)); } Temp = sb.ToString(); ConvertTextToBraille cttb1 = new ConvertTextToBraille(); TextBox.Text = cttb1.Display(Temp); reader.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
private void btnOpenPDF_Click(object sender, EventArgs e) { using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "PDF files|*.pdf", ValidateNames = true, Multiselect = false }) { if (ofd.ShowDialog() == DialogResult.OK) { try { iTextSharp.text.pdf.PdfReader read = new iTextSharp.text.pdf.PdfReader(ofd.FileName); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= read.NumberOfPages; i++) { sb.Append(PdfTextExtractor.GetTextFromPage(read, i)); } richTextBox1.Text = sb.ToString(); read.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
private System.IO.MemoryStream reorderSaddleStitchBrief(System.IO.MemoryStream orig_stream) { System.IO.MemoryStream dest_stream = null; try { dest_stream = new System.IO.MemoryStream(); var reader = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray()); var order = new SaddleStitchPageOrder(reader.NumberOfPages); reader.SelectPages(order.PageOrder); var pdfdoc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)); var pdfcopy_provider = new iTextSharp.text.pdf.PdfCopy(pdfdoc, dest_stream); pdfdoc.Open(); iTextSharp.text.pdf.PdfImportedPage importedPage; for (int i = 1; i <= reader.NumberOfPages; i++) { importedPage = pdfcopy_provider.GetImportedPage(reader, i); pdfcopy_provider.AddPage(importedPage); } pdfdoc.Close(); reader.Close(); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } return(dest_stream); }
public static bool SaddleStitch_ReorderPagesForLayout(string src) { string dest = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(src), "ss brief reordered.pdf"); try { using (var stream = new System.IO.FileStream(dest, System.IO.FileMode.Create)) { iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(src); SaddleStitchPageOrder order = new SaddleStitchPageOrder(reader.NumberOfPages); reader.SelectPages(order.PageOrder); iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)); iTextSharp.text.pdf.PdfCopy pdfcopy_provider = new iTextSharp.text.pdf.PdfCopy(pdfdoc, stream); pdfdoc.Open(); iTextSharp.text.pdf.PdfImportedPage importedPage; for (int i = 1; i <= reader.NumberOfPages; i++) { importedPage = pdfcopy_provider.GetImportedPage(reader, i); pdfcopy_provider.AddPage(importedPage); } pdfdoc.Close(); reader.Close(); } System.IO.File.Delete(src); System.IO.File.Move(dest, src); return(true); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); return(false); } }
public static bool IsPdfPageBlank(string pdf_file, int page) { var text_found = false; try { if (!System.IO.File.Exists(pdf_file)) { throw new Exception("File does not exist."); } var reader = new iTextSharp.text.pdf.PdfReader(pdf_file); var strat = new Models.Utilities.iTextSharpUtilities.MyLocationTextExtractionStrategy(); var text = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, page, strat); var re = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9\s,]*$"); if (!re.IsMatch(text)) { text_found = true; } reader.Close(); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex.Message); } return(text_found); }
public static bool CropCockleBriefPages(string src) { // works for both saddle stitch and perfect bind string dest = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(src), "brief cropped.pdf"); try { using (var stream = new System.IO.FileStream(dest, System.IO.FileMode.Create)) { iTextSharp.text.pdf.PdfRectangle croppedRectangle = new iTextSharp.text.pdf.PdfRectangle(377f, 189f, 0f, 792f); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(src); for (int i = 1; i <= reader.NumberOfPages; i++) { iTextSharp.text.pdf.PdfDictionary pageDict = reader.GetPageN(i); pageDict.Put(iTextSharp.text.pdf.PdfName.CROPBOX, croppedRectangle); } var stamper = new iTextSharp.text.pdf.PdfStamper(reader, stream); stamper.Close(); reader.Close(); } System.IO.File.Delete(src); System.IO.File.Move(dest, src); return(true); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); return(false); } }
private System.IO.MemoryStream joinTwoStreamsIntoOnePdf(System.IO.MemoryStream stream_1, System.IO.MemoryStream stream_2) { System.IO.MemoryStream dest_stream = null; try { dest_stream = new System.IO.MemoryStream(); var doc = new iTextSharp.text.Document(); var writer = new iTextSharp.text.pdf.PdfCopy(doc, dest_stream); doc.Open(); var reader_1 = new iTextSharp.text.pdf.PdfReader(stream_1.ToArray()); for (var i = 1; i <= reader_1.NumberOfPages; i++) { var page = writer.GetImportedPage(reader_1, i); writer.AddPage(page); } reader_1.Close(); var reader_2 = new iTextSharp.text.pdf.PdfReader(stream_2.ToArray()); for (var i = 1; i <= reader_2.NumberOfPages; i++) { var page = writer.GetImportedPage(reader_2, i); writer.AddPage(page); } reader_2.Close(); doc.Close(); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } return(dest_stream); }
private void button1_Click(object sender, EventArgs e) { using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "PDF files|*.pdf ", ValidateNames = true, Multiselect = false }) { if (ofd.ShowDialog() == DialogResult.OK) { try { iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(ofd.FileName); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= reader.NumberOfPages; i++) { richTextBox1.AppendText(PdfTextExtractor.GetTextFromPage(reader, i)); } richTextBox1.AppendText("toas"); reader.Close(); string res = richTextBox1.Text; breakIntoParagraphs(res); richTextBox1.Clear(); for (int i = 0; i < paragraphs.Count; i++) { richTextBox1.AppendText(paragraphs[i].mySentences[0]); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
private System.IO.MemoryStream extractPagesFromPerfectBindStream(System.IO.MemoryStream orig_stream, int start_page = 1, int end_page = 1) { System.IO.MemoryStream dest_stream = null; try { dest_stream = new System.IO.MemoryStream(); var doc = new iTextSharp.text.Document(); var writer = new iTextSharp.text.pdf.PdfCopy(doc, dest_stream); doc.Open(); var reader = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray()); for (var i = start_page; i <= end_page; i++) { var page = writer.GetImportedPage(reader, i); writer.AddPage(page); } reader.Close(); doc.Close(); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } return(dest_stream); }
public static List <FBWiFi_XMLBody> GetEmbeddedFileData(string pdfFileName, string embeddedFileName) { List <FBWiFi_XMLBody> objResult = new List <FBWiFi_XMLBody>(); byte[] attachedFileBytes = null; var reader = new iTextSharp.text.pdf.PdfReader(pdfFileName); if (reader != null) { var root = reader.Catalog; if (root != null) { var names = root.GetAsDict(iTextSharp.text.pdf.PdfName.NAMES); if (names != null) { var embeddedFiles = names.GetAsDict(iTextSharp.text.pdf.PdfName.EMBEDDEDFILES); if (embeddedFiles != null) { var namesArray = embeddedFiles.GetAsArray(iTextSharp.text.pdf.PdfName.NAMES); if (namesArray != null) { int n = namesArray.Size; for (int i = 0; i < n; i++) { i++; var fileArray = namesArray.GetAsDict(i); var file = fileArray.GetAsDict(iTextSharp.text.pdf.PdfName.EF); foreach (iTextSharp.text.pdf.PdfName key in file.Keys) { string attachedFileName = fileArray.GetAsString(key).ToString(); //if (attachedFileName == embeddedFileName) //{ var stream = (iTextSharp.text.pdf.PRStream)iTextSharp.text.pdf.PdfReader.GetPdfObject(file.GetAsIndirectObject(key)); attachedFileBytes = iTextSharp.text.pdf.PdfReader.GetStreamBytes(stream); string text = System.Text.Encoding.UTF8.GetString(attachedFileBytes); XmlSerializer serializer = new XmlSerializer(typeof(FBWiFi_XMLBody)); using (TextReader txtXML = new StringReader(text)) { FBWiFi_XMLBody result = (FBWiFi_XMLBody)serializer.Deserialize(txtXML); objResult.Add(result); } break; //} } if (attachedFileBytes != null) { break; } } } } } } reader.Close(); } return(objResult); }
public static bool CropCoverAndInsideCover(string src, int?coverLength) { // works for both saddle stitch and perfect bind string dest = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(src), "cover cropped.pdf"); try { using (var stream = new System.IO.FileStream(dest, System.IO.FileMode.Create)) { iTextSharp.text.pdf.PdfRectangle croppedRectangleCover; switch (coverLength) { case 48: default: croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 130f, 21f, 741f); break; case 49: croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 120f, 21f, 741f); break; case 50: croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 108f, 21f, 741f); break; case 51: croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 92f, 21f, 741f); break; } iTextSharp.text.pdf.PdfRectangle croppedRectangleInsideCover = new iTextSharp.text.pdf.PdfRectangle(377f, 189f, 0f, 792f); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(src); for (int i = 1; i <= reader.NumberOfPages; i++) { iTextSharp.text.pdf.PdfDictionary pageDict = reader.GetPageN(i); if (i == 1) { pageDict.Put(iTextSharp.text.pdf.PdfName.CROPBOX, croppedRectangleCover); } else { pageDict.Put(iTextSharp.text.pdf.PdfName.CROPBOX, croppedRectangleInsideCover); } } var stamper = new iTextSharp.text.pdf.PdfStamper(reader, stream); stamper.Close(); reader.Close(); } System.IO.File.Delete(src); System.IO.File.Move(dest, src); return(true); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); return(false); } }
private string GetPdfText(string userFilePath) { using var reader = new iTextSharp.text.pdf.PdfReader(userFilePath); var text = string.Empty; for (int page = 1; page <= reader.NumberOfPages; page++) { text += iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, page); } reader.Close(); return(text); }
private System.IO.MemoryStream imposeTypesetPerfectBindCover(System.IO.MemoryStream orig_stream) { System.IO.MemoryStream dest_stream = null; try { dest_stream = new System.IO.MemoryStream(); var docB4 = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(1031.76f, 728.64f)); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(docB4, dest_stream); docB4.Open(); var reader = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray()); iTextSharp.text.pdf.PdfContentByte contentbyte; docB4.Add(new iTextSharp.text.Chunk()); iTextSharp.text.pdf.PdfTemplate tCover = writer.GetImportedPage(reader, 1); contentbyte = writer.DirectContent; // default values: in PB briefs, y_coordinate will not vary float x_coordinate = 575.5f, y_coordinate = -76.5f; switch (LengthOfCover) { default: case 48: // GOOD: TESTED 11/16/15 y_coordinate = -88.5f; break; case 49: // STILL AN ESTIMATE y_coordinate = -82.5f; break; case 50: // GOOD: TESTED 11/16/15 y_coordinate = -76.5f; break; case 51: // GOOD: TESTED 11/16/15 y_coordinate = -70.5f; break; } contentbyte.AddTemplate(tCover, x_coordinate, y_coordinate); docB4.Close(); reader.Close(); writer.Close(); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } return(dest_stream); }
private void btnConverterPDF_Click(object sender, EventArgs e) { iTextSharp.text.pdf.PdfReader leitor = new iTextSharp.text.pdf.PdfReader(txtCaminoNomePDF.Text); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= leitor.NumberOfPages; i++) { sb.Append(PdfTextExtractor.GetTextFromPage(leitor, i)); } rTxt_texto.Text = sb.ToString(); leitor.Close(); }
public static bool PerfectBind_LayoutCroppedBrief(string src) { string dest = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(src), "pb on B5.pdf"); try { using (var stream = new System.IO.FileStream(dest, System.IO.FileMode.Create)) { iTextSharp.text.Document docB5 = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(515.76f, 728.4f)); // B5 sized page iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(docB5, stream); docB5.Open(); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(src); for (int i = 1; i <= reader.NumberOfPages; i++) { if (i != 1) { docB5.NewPage(); } docB5.Add(new iTextSharp.text.Chunk()); iTextSharp.text.pdf.PdfTemplate t = writer.GetImportedPage(reader, i); iTextSharp.text.pdf.PdfContentByte contentbyte = writer.DirectContent; // MEASUREMENTS GOOD: TESTED 11/16/2015 if (i % 2 == 1) { contentbyte.AddTemplate(t, /*42.5f*/ 35.5f, -141.75f); // position for front side of B5 sheet } else if (i % 2 == 0) { contentbyte.AddTemplate(t, /*110f*/ 110f, -141.75f); // position for back side of B5 sheet } else { throw new Exception(); } } docB5.Close(); reader.Close(); } System.IO.File.Delete(src); System.IO.File.Move(dest, src); return(true); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); return(false); } }
protected override void Execute(CodeActivityContext context) { var filename = Filename.Get(context); filename = Environment.ExpandEnvironmentVariables(filename); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(filename); context.SetValue(Result, reader); var result = GetTextFromAllPages(reader); context.SetValue(AllText, result); if (Result == null || Result.GetIsEmpty()) { reader.Close(); } }
private static string GetPdfText_Itextsharp(iTextSharp.text.pdf.PdfReader reader) { System.Text.StringBuilder builder = new System.Text.StringBuilder(); int n = reader.NumberOfPages; for (int i = 1; i <= n; i++) { string text = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, i); //text = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(text))); builder.Append(text); } try { reader.Close(); } catch { } return(builder.ToString()); }
/* ----------------------------------------------------------------- */ /// /// IsProtected /// /// <summary> /// 指定した PDF ファイルがパスワードによるセキュリティが設定され /// ているかどうか判定する. /// </summary> /// /* ----------------------------------------------------------------- */ private static bool IsProtected(string path) { bool status = false; try { var test = new iTextSharp.text.pdf.PdfReader(path); status = !test.IsOpenedWithFullPermissions; test.Close(); } catch (iTextSharp.text.pdf.BadPasswordException /* err */) { status = true; } return(status); }
public static List <System.Drawing.Image> ExtractImagesFromPDF(String PDFSourcePath) { List <System.Drawing.Image> ImgList = new List <System.Drawing.Image>(); iTextSharp.text.pdf.RandomAccessFileOrArray RAFObj = null; iTextSharp.text.pdf.PdfReader PDFReaderObj = null; iTextSharp.text.pdf.PdfObject PDFObj = null; iTextSharp.text.pdf.PdfStream PDFStremObj = null; try { RAFObj = new iTextSharp.text.pdf.RandomAccessFileOrArray(PDFSourcePath); PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj, null); for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++) { PDFObj = PDFReaderObj.GetPdfObject(i); if ((PDFObj != null) && PDFObj.IsStream()) { PDFStremObj = (iTextSharp.text.pdf.PdfStream)PDFObj; iTextSharp.text.pdf.PdfObject subtype = PDFStremObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE); if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString()) { try { iTextSharp.text.pdf.parser.PdfImageObject PdfImageObj = new iTextSharp.text.pdf.parser.PdfImageObject((iTextSharp.text.pdf.PRStream)PDFStremObj); System.Drawing.Image ImgPDF = PdfImageObj.GetDrawingImage(); ImgList.Add(ImgPDF); } catch (Exception) { } } } } PDFReaderObj.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } return(ImgList); }
public virtual void manipulatePdf(string src, string dest) { PdfReader reader = new PdfReader(src); PdfStamper stamper = new PdfStamper(reader, new System.IO.FileStream(dest, System.IO.FileMode.Create, System.IO.FileAccess.Write)); stamper.RotateContents = false; Phrase header = new Phrase("Copy", new Font(Font.FontFamily.HELVETICA, 14)); for (int i = 1; i <= reader.NumberOfPages; i++) { float x = reader.GetPageSize(i).Width / 2; float y = reader.GetPageSize(i).GetTop(20); ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_CENTER, header, x, y, 0); } stamper.Close(); reader.Close(); }
public void ExtractPage(string sourcePdfPath, string outputPdfPath, int pageNumber, int pageend) { iTextSharp.text.pdf.PdfReader reader = null; iTextSharp.text.Document document = null; iTextSharp.text.pdf.PdfCopy pdfCopyProvider = null; iTextSharp.text.pdf.PdfImportedPage importedPage = null; try { // Intialize a new PdfReader instance with the contents of the source Pdf file: reader = new iTextSharp.text.pdf.PdfReader(sourcePdfPath); // Capture the correct size and orientation for the page: document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(pageNumber)); // Initialize an instance of the PdfCopyClass with the source // document and an output file stream: pdfCopyProvider = new iTextSharp.text.pdf.PdfCopy(document, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create)); document.Open(); // Extract the desired page number: if (pageNumber == pageend) { importedPage = pdfCopyProvider.GetImportedPage(reader, pageNumber + 1); pdfCopyProvider.AddPage(importedPage); } else { for (int i = pageNumber; i <= pageend; i++) { importedPage = pdfCopyProvider.GetImportedPage(reader, i + 1); pdfCopyProvider.AddPage(importedPage); } } document.Close(); reader.Close(); } catch (Exception ex) { _arCommonService.CreateErrorLog(ex.Message, ex.StackTrace); } }
/* ----------------------------------------------------------------- */ /// /// IsValidPassword /// /// <summary> /// 指定したパスワードが有効であるかどうかを判定する. /// </summary> /// /* ----------------------------------------------------------------- */ private static bool IsValidPassword(string path, string password) { var status = true; try { var test = new iTextSharp.text.pdf.PdfReader(path, System.Text.Encoding.UTF8.GetBytes(password)); if (!test.IsOpenedWithFullPermissions) { status = false; } test.Close(); } catch (Exception /* err */) { status = false; } return(status); }
private System.IO.MemoryStream cropTypesetCover(System.IO.MemoryStream orig_stream) { { // works for both saddle stitch and perfect bind System.IO.MemoryStream dest_stream = null; try { dest_stream = new System.IO.MemoryStream(); iTextSharp.text.pdf.PdfRectangle croppedRectangleCover; switch (LengthOfCover) { case 48: default: croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 130f, 21f, 741f); break; case 49: croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 120f, 21f, 741f); break; case 50: croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 108f, 21f, 741f); break; case 51: croppedRectangleCover = new iTextSharp.text.pdf.PdfRectangle(356f, 92f, 21f, 741f); break; } var reader = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray()); var pageDict = reader.GetPageN(1); pageDict.Put(iTextSharp.text.pdf.PdfName.CROPBOX, croppedRectangleCover); var stamper = new iTextSharp.text.pdf.PdfStamper(reader, dest_stream); stamper.Close(); reader.Close(); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } return(dest_stream); } }
private System.IO.MemoryStream imposeTypesetPerfectBindBrief(System.IO.MemoryStream orig_stream) { System.IO.MemoryStream dest_stream = null; try { dest_stream = new System.IO.MemoryStream(); var docB5 = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(515.76f, 728.4f)); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(docB5, dest_stream); docB5.Open(); var reader = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray()); for (int i = 1; i <= reader.NumberOfPages; i++) { if (i != 1) { docB5.NewPage(); } docB5.Add(new iTextSharp.text.Chunk()); iTextSharp.text.pdf.PdfTemplate t = writer.GetImportedPage(reader, i); iTextSharp.text.pdf.PdfContentByte contentbyte = writer.DirectContent; // MEASUREMENTS GOOD: TESTED 11/16/2015 if (i % 2 == 1) { contentbyte.AddTemplate(t, /*42.5f*/ 35.5f, -141.75f); // position for front side of B5 sheet } else if (i % 2 == 0) { contentbyte.AddTemplate(t, /*110f*/ 110f, -141.75f); // position for back side of B5 sheet } } docB5.Close(); reader.Close(); writer.Close(); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } return(dest_stream); }
private System.IO.MemoryStream cropTypesetBrief(System.IO.MemoryStream orig_stream) { System.IO.MemoryStream dest_stream = null; try { dest_stream = new System.IO.MemoryStream(); var croppedRectangle = new iTextSharp.text.pdf.PdfRectangle(377f, 189f, 0f, 792f); var reader = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray()); for (int i = 1; i <= reader.NumberOfPages; i++) { iTextSharp.text.pdf.PdfDictionary pageDict = reader.GetPageN(i); pageDict.Put(iTextSharp.text.pdf.PdfName.CROPBOX, croppedRectangle); } var stamper = new iTextSharp.text.pdf.PdfStamper(reader, dest_stream); stamper.Close(); reader.Close(); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); } return(dest_stream); }
public string ExtractTextFromRegionOfPdf(string sourceFileName) { FileStream x = new FileStream(sourceFileName, FileMode.Open); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(x); //AWESOME!! System.util.RectangleJ rect1 = new System.util.RectangleJ(Rect.X, System.Math.Abs(this.PictureBox1.Height - Rect.Y) - Rect.Height, Rect.Width, Rect.Height); iTextSharp.text.pdf.parser.RegionTextRenderFilter rf = new iTextSharp.text.pdf.parser.RegionTextRenderFilter(rect1); iTextSharp.text.pdf.parser.LocationTextExtractionStrategy mystrat = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy(); iTextSharp.text.pdf.parser.RegionTextRenderFilter[] rtrf = new iTextSharp.text.pdf.parser.RegionTextRenderFilter[2]; rtrf[0] = rf; //Dim rect2 As New System.util.RectangleJ(0, 700, 800, 140) //Dim rf2 As New iTextSharp.text.pdf.parser.RegionTextRenderFilter(rect2) iTextSharp.text.pdf.parser.FilteredTextRenderListener textExtractionStrategy = new iTextSharp.text.pdf.parser.FilteredTextRenderListener(mystrat, rtrf); //rtrf(0) = rf2 //textExtractionStrategy = New iTextSharp.text.pdf.parser.FilteredTextRenderListener(mystrat, rtrf) //MsgBox(iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, 1, textExtractionStrategy)) // iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, 1, textExtractionStrategy) x.Close(); x.Dispose(); reader.Close(); if (_mode == 1) { if (this.loadedbool) { string s = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, CurrentPage + 1, textExtractionStrategy); DialogResult y = MessageBox.Show("This field is showing : " + s + "\r\n" + "Is this the correct variable on this page?","Confirm" , MessageBoxButtons.YesNo ); if (y == DialogResult.Yes ) { _dtt.Rows[_CurrentCount]["x"] = Rect.X; _dtt.Rows[_CurrentCount]["y"] = System.Math.Abs(this.PictureBox1.Height - Rect.Y) - Rect.Height; _dtt.Rows[_CurrentCount]["width"] = Rect.Width; _dtt.Rows[_CurrentCount]["height"] = Rect.Height; if (_CurrentCount == 0) { DialogResult xx = MessageBox.Show("There is an optional Parimeter where you can select something that only appears on the first page, do you want to add this. It can be part of a string like Page 1 of XX?", "Confirm", MessageBoxButtons.YesNo); if (xx == DialogResult.No) { _CurrentCount = 2; } } if (_dtt.Rows[_CurrentCount]["FieldName"] == "FirstPageConstant") { _validatetext = Interaction.InputBox("Enter Charectors to match, if you enter \"1 of \" it will be true for anything after the of"); _dtt.Rows[_CurrentCount + 1]["misc"] = _validatetext; _CurrentCount += 1; } _CurrentCount += 1; if (_CurrentCount == 3) { _CurrentCount = 0; this.Label2.Text = "OK, you have completed the template, if you wish to start over simply do it again and start by selecting the area with:" + _dtt.Rows[0]["fieldname"]; startover = 1; drawrectangles(); MessageBox.Show("Make sure you save this if you want to use it in the future."); } else { this.Label2.Text = "Now Select : " + _dtt.Rows[_CurrentCount]["fieldname"]; } } } } else { this.Label2.Text = "OK, you have completed the template, if you wish to start over simply do it again and start by selecting the area with:" + _dtt.Rows[0]["fieldname"]; } return ""; }
public void verify() { addresscollection aic = new addresscollection(); addressitem ai = null; string sourceFileName = _sourcefilename; FileStream x = new FileStream(sourceFileName, FileMode.Open); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(x); //AWESOME!! x.Close(); x.Dispose(); string s = ""; string s1 = ""; System.Xml.XmlNode ep = null; System.Xml.XmlNode batch = null; System.Xml.XmlNode startingpage = null; System.Xml.XmlNode envelope = null; int pages = reader.NumberOfPages; int i; for (i = 0; i <= reader.NumberOfPages - 1; i++) { this.Label2.Invoke(new updatetext(updatelabel1text), new object[] { "Processing Page " + Convert.ToString(i + 1) + " of " + pages }); DataRow dr = _dtt.Rows[0]; System.util.RectangleJ rect1 = new System.util.RectangleJ(Convert.ToInt32( dr["x"]), Convert.ToInt32( dr["y"]), Convert.ToInt32( dr["width"]), Convert.ToInt32( dr["height"])); iTextSharp.text.pdf.parser.RegionTextRenderFilter rf = new iTextSharp.text.pdf.parser.RegionTextRenderFilter(rect1); iTextSharp.text.pdf.parser.LocationTextExtractionStrategy mystrat = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy(); iTextSharp.text.pdf.parser.RegionTextRenderFilter[] rtrf = new iTextSharp.text.pdf.parser.RegionTextRenderFilter[2]; rtrf[0] = rf; //Dim rect2 As New System.util.RectangleJ(0, 700, 800, 140) //Dim rf2 As New iTextSharp.text.pdf.parser.RegionTextRenderFilter(rect2) iTextSharp.text.pdf.parser.FilteredTextRenderListener textExtractionStrategy = new iTextSharp.text.pdf.parser.FilteredTextRenderListener(mystrat, rtrf); DataRow dr1 = _dtt.Rows[1]; System.util.RectangleJ rect2 = new System.util.RectangleJ(Convert.ToInt32( dr1["x"]), Convert.ToInt32( dr1["y"]), Convert.ToInt32( dr1["width"]), Convert.ToInt32( dr1["height"])); iTextSharp.text.pdf.parser.RegionTextRenderFilter rf1 = new iTextSharp.text.pdf.parser.RegionTextRenderFilter(rect2); iTextSharp.text.pdf.parser.LocationTextExtractionStrategy mystrat1 = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy(); iTextSharp.text.pdf.parser.RegionTextRenderFilter[] rtrf1 = new iTextSharp.text.pdf.parser.RegionTextRenderFilter[2]; rtrf1[0] = rf1; //Dim rect2 As New System.util.RectangleJ(0, 700, 800, 140) //Dim rf2 As New iTextSharp.text.pdf.parser.RegionTextRenderFilter(rect2) iTextSharp.text.pdf.parser.FilteredTextRenderListener textExtractionStrategy1 = new iTextSharp.text.pdf.parser.FilteredTextRenderListener(mystrat1, rtrf1); s = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, i + 1, textExtractionStrategy); if (!string.IsNullOrEmpty(s)) { s1 = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, i + 1, textExtractionStrategy1); if (parseaddress(s, s1, ref batch, i + 1, ref ep, ref envelope, ref startingpage, ref ai)) { //Des not catch a single first page, anytime this is true it's a new first page // ep.InnerText = i + 1 // Console.WriteLine(ai.Address1) aic.Add(ai); } } if (i == reader.NumberOfPages - 1 & (ep != null)) { ep.InnerText = Convert.ToString(i + 1); } if (i == reader.NumberOfPages - 1 & (ai != null)) { ai.endpage = Convert.ToInt32( i + 1); } // CurrentPage = CurrentPage + 1 } reader.Close(); //Me.RichTextBox1.Invoke(New updatert(AddressOf updaterichtext), New Object() {XMLDOC.OuterXml, badaddress}) this.RichTextBox1.Invoke(new updatert(updaterichtext), new object[] { XMLDOC, badaddress }); //Me.RichTextBox1.Invoke(New updatert(AddressOf updaterichtext), New Object() {badaddress}) Invoke(new updatedatagrid(updatedatagridonMail), new object[] { aic }); Invoke(new updatecomplete(updatecompleted), new object[]{}); //rtrf(0) = rf2 //textExtractionStrategy = New iTextSharp.text.pdf.parser.FilteredTextRenderListener(mystrat, rtrf) //MsgBox(iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, 1, textExtractionStrategy)) // iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, 1, textExtractionStrategy) }
/* ----------------------------------------------------------------- */ /// /// IsValidPassword /// /// <summary> /// 指定したパスワードが有効であるかどうかを判定する. /// </summary> /// /* ----------------------------------------------------------------- */ private static bool IsValidPassword(string path, string password) { var status = true; try { var test = new iTextSharp.text.pdf.PdfReader(path, System.Text.Encoding.UTF8.GetBytes(password)); if (!test.IsOpenedWithFullPermissions) status = false; test.Close(); } catch (Exception /* err */) { status = false; } return status; }
private void verifySingleItem() { addresscollection aic = new addresscollection(); string sourceFileName = _sourcefilename; FileStream x = new FileStream(sourceFileName, FileMode.Open); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(x); //AWESOME!! // x.Close() //x.Dispose() string s = ""; string s1 = ""; System.Xml.XmlNode ep = null; System.Xml.XmlNode batch = null; int pages = reader.NumberOfPages; reader.Close(); x.Close(); if (parseaddresssingle(ref _aiSingle, pages)) { //Des not catch a single first page, anytime this is true it's a new first page // ep.InnerText = i + 1 // Console.WriteLine(ai.Address1) } aic.Add(_aiSingle); reader.Close(); //Me.RichTextBox1.Invoke(New updatert(AddressOf updaterichtext), New Object() {XMLDOC.OuterXml, badaddress}) Invoke(new updatert(updaterichtext), new object[] { XMLDOC, badaddress }); //Me.RichTextBox1.Invoke(New updatert(AddressOf updaterichtext), New Object() {badaddress}) Invoke(new updatedatagrid(updatedatagridonMail), new object[] { aic }); Invoke(new updatecomplete(updatecompleted), new object[]{}); //rtrf(0) = rf2 //textExtractionStrategy = New iTextSharp.text.pdf.parser.FilteredTextRenderListener(mystrat, rtrf) //MsgBox(iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, 1, textExtractionStrategy)) // iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, 1, textExtractionStrategy) }
/// <summary> /// Uses the GetResponseCore and GetResponseCoreFinalize to 'inherit' the IFilter behaviour /// but also extend it with iTextSharp /// </summary> /// <remarks> /// Add iTextSharp to get better 'title' /// [v7] fix by [email protected] /// </remarks> public override bool GetResponse(System.Net.HttpWebResponse webresponse) { string filename = System.IO.Path.Combine(Preferences.DownloadedTempFilePath, (System.IO.Path.GetFileName(this.Uri.LocalPath))); base.GetResponseCore(webresponse, filename); // [v7] fix by [email protected] iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(filename); if (null != pdfReader.Info["Title"]) { // overwrite the 'filename' with the embedded title string pdfTitle = Convert.ToString(pdfReader.Info["Title"]).Trim(); if (!String.IsNullOrEmpty(pdfTitle)) { this.Title = pdfTitle; } } // Now, since we've loaded the iTextSharp library, and the EPocalipse IFilter sometimes // fails (old Acrobat, installation problem, etc); let's try 'indexing' the PDF with iTextSharp // [v7] if (String.IsNullOrEmpty(this.All)) { this.All = String.Empty; System.Text.StringBuilder sb = new System.Text.StringBuilder(); // Following code from: // http://www.vbforums.com/showthread.php?t=475759 for (int p = 1; p <= pdfReader.NumberOfPages; p++) { byte[] pageBytes = pdfReader.GetPageContent(p); if (null != pageBytes) { iTextSharp.text.pdf.PRTokeniser token = new iTextSharp.text.pdf.PRTokeniser(new iTextSharp.text.pdf.RandomAccessFileOrArray(pageBytes)); while (token.NextToken()) { iTextSharp.text.pdf.PRTokeniser.TokType tknType = token.TokenType; string tknValue = token.StringValue; if (tknType == iTextSharp.text.pdf.PRTokeniser.TokType.STRING) { sb.Append(token.StringValue); } else if (tknType == iTextSharp.text.pdf.PRTokeniser.TokType.NUMBER && tknValue == "-600") { sb.Append(" "); } else if (tknType == iTextSharp.text.pdf.PRTokeniser.TokType.OTHER && tknValue == "TJ") { sb.Append(" "); } } } } this.All += sb.ToString().Replace('\0', ' '); } pdfReader.Close(); base.GetResponseCoreFinalize(filename); if (!String.IsNullOrEmpty(this.All)) { this.Description = base.GetDescriptionFromWordsOnly(WordsOnly); return true; } else { return false; } }
private void verifysendsingletomultiple(string xtemplate, DataTable dt) { addresscollection aic = new addresscollection(); string x = null; x = xtemplate; System.Xml.XmlNode batchnode = null; System.Xml.XmlNode recipients = null; FileStream x1 = new FileStream(_sourcefilename, FileMode.Open); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(x1); //AWESOME!! x1.Close(); x1.Dispose(); string s = ""; string s1 = ""; int nop = reader.NumberOfPages; reader.Close(); System.Xml.XmlNode ep = null; System.Xml.XmlNode batch = null; int pages = reader.NumberOfPages; int i = 0; foreach (DataRow r in dt.Rows) { this.Label2.Invoke(new updatetext(updatelabel1text), new object[] { "Processing Page " + (i + 1) + " of " + dt.Rows.Count }); i += 1; foreach (DataColumn c in dt.Columns) { try { if ((!object.ReferenceEquals(dt.Rows[1][c], DBNull.Value))) { x = Strings.Replace(x, "{" + c.ColumnName + "}", (string) r[c]); } else { x = Strings.Replace(x, "{" + c.ColumnName + "}", ""); } } catch { } } x = Regex.Replace(x, "^\\s+$[\\r\\n]*", "", RegexOptions.Multiline); addressitem ai = null; if (parseaddresssingledoctomultiple(ref ai, ref batchnode, x, 1, nop, i, ref recipients)) { } //EVERY PAGE IS GOOD aic.Add(ai); x = xtemplate; } //Me.DataGridView2.DataSource = aic this.RichTextBox1.Invoke(new updatert(updaterichtext), new object[] { XMLDOC, badaddress }); //Me.RichTextBox1.Invoke(New updatert(AddressOf updaterichtext), New Object() {badaddress}) Invoke(new updatedatagrid(updatedatagridonMail), new object[] { aic }); Invoke(new updatecomplete(updatecompleted), new object[]{}); }
/* ----------------------------------------------------------------- */ /// /// IsProtected /// /// <summary> /// 指定した PDF ファイルがパスワードによるセキュリティが設定され /// ているかどうか判定する. /// </summary> /// /* ----------------------------------------------------------------- */ private static bool IsProtected(string path) { bool status = false; try { var test = new iTextSharp.text.pdf.PdfReader(path); status = !test.IsOpenedWithFullPermissions; test.Close(); } catch (iTextSharp.text.pdf.BadPasswordException /* err */) { status = true; } return status; }
/* ----------------------------------------------------------------- */ /// /// AddInformation /// /// <summary> /// PDF ファイルに対して、引数に指定されたユーザ設定にしたがって /// 必要な情報を付与します。 /// </summary> /// /// <remarks> /// iTextSharp を用いて以下の情報を付与します。 /// /// - 文書プロパティ /// - 文書を開くためのパスワード (UserPassword) /// - 権限編集のためのパスワード (OwnerPassword) /// - 各種パーミッション /// </remarks> /// /* ----------------------------------------------------------------- */ private bool AddInformation(UserSetting setting) { if (!CubePdf.Misc.File.Exists(setting.OutputPath)) return false; string tmp = Utility.WorkingDirectory + '\\' + System.IO.Path.GetRandomFileName(); iTextSharp.text.pdf.PdfReader reader = null; bool status = true; try { CubePdf.Misc.File.Move(setting.OutputPath, tmp, true); reader = new iTextSharp.text.pdf.PdfReader(tmp); var writer = new iTextSharp.text.pdf.PdfStamper(reader, new System.IO.FileStream(setting.OutputPath, System.IO.FileMode.Create), PdfVersionToiText(setting.PDFVersion)); // 文書プロパティ Dictionary<string, string> info = new Dictionary<string, string>(); info["Title"] = setting.Document.Title; info["Author"] = setting.Document.Author; info["Subject"] = setting.Document.Subtitle; info["Keywords"] = setting.Document.Keyword; info["Creator"] = Properties.Resources.ProductName; info["Producer"] = Properties.Resources.ProductName; writer.MoreInfo = info; // デバッグログ var message = new System.Text.StringBuilder(); message.AppendLine("iTextSharp.text.pdf.PdfStamper.MoreInfo"); message.AppendLine(String.Format("\tTitle = {0}", info["Title"])); message.AppendLine(String.Format("\tAuthor = {0}", info["Author"])); message.AppendLine(String.Format("\tSubject = {0}", info["Subject"])); message.Append( String.Format("\tKeywords = {0}", info["Keywords"])); _messages.Add(new Message(Message.Levels.Debug, message.ToString())); // パスワード and/or パーミッション string user = !string.IsNullOrEmpty(setting.Password) ? setting.Password : string.Empty; string owner = !string.IsNullOrEmpty(setting.Permission.Password) ? setting.Permission.Password : string.Empty; if (string.IsNullOrEmpty(owner) && !string.IsNullOrEmpty(user)) owner = user; int permission = this.PermissionToiText(setting.Permission); if (!string.IsNullOrEmpty(user) || !string.IsNullOrEmpty(owner)) { writer.SetEncryption(iTextSharp.text.pdf.PdfWriter.STANDARD_ENCRYPTION_128, user, owner, permission); } writer.Close(); } catch (Exception err) { _messages.Add(new Message(Message.Levels.Error, err)); _messages.Add(new Message(Message.Levels.Debug, err)); status = false; } finally { if (reader != null) reader.Close(); if (CubePdf.Misc.File.Exists(tmp)) { if (!CubePdf.Misc.File.Exists(setting.OutputPath)) CubePdf.Misc.File.Move(tmp, setting.OutputPath, true); else { var fi = new System.IO.FileInfo(setting.OutputPath); if (fi.Length == 0) CubePdf.Misc.File.Move(tmp, setting.OutputPath, true); else CubePdf.Misc.File.Delete(tmp, false); } } } return status; }
/// <summary> /// Return a page count for pdf /// </summary> /// <param name="pdfPath"></param> /// <returns></returns> public int PDFPageCount(string pdfPath) { try { iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(pdfPath); int pageCount = pdfReader.NumberOfPages; pdfReader.Close(); return pageCount; } catch (Exception) { return 0; } }