private void button1_Click(object sender, EventArgs e) { String input = @"..\..\..\..\..\..\Data\SearchReplaceTemplate.pdf"; PdfDocument doc = new PdfDocument(); // Read a pdf file doc.LoadFromFile(input); // Get the first page of pdf file PdfPageBase page = doc.Pages[0]; // Create PdfTextFindCollection object to find all the matched phrases PdfTextFindCollection collection = page.FindText("e-iceblue", TextFindParameter.IgnoreCase); // hyperlink url String url = "http://www.e-iceblue.com"; foreach (PdfTextFind find in collection.Finds) { // Create a PdfUriAnnotation object to add hyperlink for the searched text PdfUriAnnotation uri = new PdfUriAnnotation(find.Bounds); uri.Uri = url; uri.Border = new PdfAnnotationBorder(1f); uri.Color = Color.Blue; page.AnnotationsWidget.Add(uri); } String result = "SearchTextAndAddHyperlink_out.pdf"; //Save the document doc.SaveToFile(result); //Launch the Pdf file PDFDocumentViewer(result); }
private void button1_Click(object sender, EventArgs e) { String input = @"..\..\..\..\..\..\Data\SearchReplaceTemplate.pdf"; PdfDocument doc = new PdfDocument(); // Read a pdf file doc.LoadFromFile(input); // Get the first page of pdf file PdfPageBase page = doc.Pages[0]; // Create PdfTextFindCollection object to find all the matched phrases PdfTextFindCollection collection = page.FindText("Spire.PDF for .NET", TextFindParameter.IgnoreCase); // Create a StringBuilder object to put the details of the text searched StringBuilder builder = new StringBuilder(); foreach (PdfTextFind find in collection.Finds) { builder.AppendLine("=================================================================================="); builder.AppendLine("Match Text: " + find.MatchText); builder.AppendLine("Text: " + find.SearchText); builder.AppendLine("Size: " + find.Size); builder.AppendLine("Position: " + find.Position); builder.AppendLine("The index of page which is including the searched text : " + find.SearchPageIndex); builder.AppendLine("The line that contains the searched text : " + find.LineText); builder.AppendLine("Match Text: " + find.MatchText); } String result = "GetDetailsOfSearchedText_out.txt"; File.WriteAllText(result, builder.ToString()); //Launch the result file DocumentViewer(result); }
private void button1_Click(object sender, EventArgs e) { String input = @"..\..\..\..\..\..\Data\SearchReplaceTemplate.pdf"; PdfDocument doc = new PdfDocument(); // Read a pdf file doc.LoadFromFile(input); // Get the first page of pdf file PdfPageBase page = doc.Pages[0]; // Create PdfTextFindCollection object to find all the matched phrases PdfTextFindCollection collection = page.FindText("Spire.PDF for .NET", TextFindParameter.IgnoreCase); foreach (PdfTextFind find in collection.Finds) { // Draw a rectangle with red pen page.Canvas.DrawRectangle(new PdfPen(PdfBrushes.Red, 0.9f), find.Bounds); } String result = "SearchTextAndDrawRectangle_out.pdf"; //Save the document doc.SaveToFile(result); //Launch the Pdf file PDFDocumentViewer(result); }
static void Main(string[] args) { //Initialize an instance of PdfDocument class and load the file PdfDocument doc = new PdfDocument(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf"); //Get the first page PdfPageBase page = doc.Pages[0]; //Call the FindText() method to find the text which is needed to add annotation PdfTextFind[] results = page.FindText("IPCC").Finds; //Specify the location of annotation float x = results[0].Position.X - doc.PageSettings.Margins.Top; float y = results[0].Position.Y - doc.PageSettings.Margins.Left + results[0].Size.Height - 23; //Create the pop-up annotation RectangleF rect = new RectangleF(x, y, 15, 0); PdfPopupAnnotation popupAnnotation = new PdfPopupAnnotation(rect); //Add the text into the annotation and set the icon and color popupAnnotation.Text = "IPCC,This is a scientific and intergovernmental body under the auspices of the United Nations."; popupAnnotation.Icon = PdfPopupIcon.Help; popupAnnotation.Color = Color.SandyBrown; //Add the annotation to the PDF file page.AnnotationsWidget.Add(popupAnnotation); //Save the file and view doc.SaveToFile("Annotation.pdf"); System.Diagnostics.Process.Start("Annotation.pdf"); }
//向签发日期后添加日期 /// <summary> /// 向签发日期后添加日期 /// </summary> /// <param name="oldPath"></param> /// <param name="newPath"></param> /// <param name="flagTxt">要查找的字符串</param> /// <param name="issueDate">要写入的日期</param> public void addIssueDateToPdf(string oldPath, string newPath, string flagTxt, string issueDate) { try { //Create a pdf document PdfDocument doc = new PdfDocument(); doc.LoadFromFile(oldPath); PdfPageBase page = null; PdfTextFind[] result = null; for (int i = 2; i < doc.Pages.Count; i++) { page = doc.Pages[i]; try { //pdfTextFindCollection = page.FindText(flagTxt); //pdfTextFindCollection = page.ExecuteCommandFindText(flagTxt); PdfTextFindCollection pdfTextFindCollection = page.FindText(flagTxt); result = pdfTextFindCollection.Finds; }catch (Exception ex) { classLims_NPOI.WriteLog("查询标记字符串时出错,可能是文件损坏或编码格式错误!\n" + ex.ToString(), ""); continue; } if (result.Length > 0) { break; } } //如果没找到标记字符串,记录并返回 if (result == null || result.Length == 0) { classLims_NPOI.WriteLog("标记字符串未找到", ""); return; } //获取第一次出现文字的坐标,宽度和高度 PointF pointf = result[0].Position; //获取文字的宽高 SizeF size = result[0].Size; AlignText(page, issueDate, pointf.X + size.Width + 50, pointf.Y + 3); //save pdf file doc.SaveToFile(newPath); doc.Close(); } catch (Exception ex) { classLims_NPOI.WriteLog(ex, ""); } }
private void button1_Click(object sender, EventArgs e) { String input = @"..\..\..\..\..\..\Data\SearchReplaceTemplate.pdf"; PdfDocument doc = new PdfDocument(); // Read a pdf file doc.LoadFromFile(input); // Get the first page of pdf file PdfPageBase page = doc.Pages[0]; // Create PdfTextFindCollection object to find all the phrases matching the regular expression PdfTextFindCollection collection = page.FindText("\\d{4}", TextFindParameter.IgnoreCase); String newText = "New Year"; // Creates a brush PdfBrush brush = new PdfSolidBrush(Color.DarkBlue); // Defines a font PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 7f, FontStyle.Bold)); // Defines text horizontal/vertical center format PdfStringFormat centerAlign = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle); RectangleF rec; foreach (PdfTextFind find in collection.Finds) { // Gets the bound of the found text in page rec = find.Bounds; page.Canvas.DrawRectangle(PdfBrushes.GreenYellow, rec); // Draws new text as defined font and color page.Canvas.DrawString(newText, font, brush, rec, centerAlign); // This method can directly replace old text with newText,but it just can set the background color, can not set font/forecolor // find.ApplyRecoverString(newText, Color.Gray); } String result = "ReplaceTextWithRegularExpression_out.pdf"; //Save the document doc.SaveToFile(result); //Launch the Pdf file PDFDocumentViewer(result); }
private void button1_Click(object sender, EventArgs e) { String input = @"..\..\..\..\..\..\Data\SearchReplaceTemplate.pdf"; PdfDocument doc = new PdfDocument(); // Read a pdf file doc.LoadFromFile(input); // Get the first page of pdf file PdfPageBase page = doc.Pages[0]; // Searches "Spire.PDF for .NET" by ignoring case PdfTextFindCollection collection = page.FindText("Spire.PDF for .NET", TextFindParameter.IgnoreCase); String newText = "E-iceblue Spire.PDF"; // Creates a brush PdfBrush brush = new PdfSolidBrush(Color.DarkBlue); // Defines a font PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 12f, FontStyle.Regular)); RectangleF rec; foreach (PdfTextFind find in collection.Finds) { // Gets the bound of the found text in page rec = find.Bounds; page.Canvas.DrawRectangle(PdfBrushes.White, rec); // Draws new text as defined font and color page.Canvas.DrawString(newText, font, brush, rec); // This method can directly replace old text with newText,but it just can set the background color, can not set font/forecolor // find.ApplyRecoverString(newText, Color.Gray); } String result = "ReplaceAllSearchedText_out.pdf"; //Save the document doc.SaveToFile(result); //Launch the Pdf file PDFDocumentViewer(result); }
public MemoryStream FillReport(Student student, ReportDetails details) { List <string> tagsToFind = new List <string>() { "$subject", "$topicno", "$author", "$teacher", "$year", "$major", "$typeofstudies", "$semester", "$labdate", "$group", "$section", "$deadlinedate", "$returneddate" }; foreach (String tag in tagsToFind) { PdfPageBase page = template.Pages[0]; PdfTextFind location = page.FindText(tag, TextFindParameter.None)?.Finds[0]; if (location != null) { string replacement; PdfTrueTypeFont font; switch (tag) { case "$subject": replacement = details.Subject; font = new PdfTrueTypeFont(new Font("Calibri", 18f, FontStyle.Bold)); break; case "$topicno": replacement = details.TopicNo.ToString(); font = new PdfTrueTypeFont(new Font("Calibri", 18f, FontStyle.Regular)); break; case "$author": replacement = student.Name; font = new PdfTrueTypeFont(new Font("Calibri", 12f, FontStyle.Regular)); break; case "$teacher": replacement = details.TeacherName; font = new PdfTrueTypeFont(new Font("Calibri", 12f, FontStyle.Regular)); break; case "$year": replacement = DateTime.Now.Month < 10 ? (DateTime.Now.Year - 1).ToString() + "/" + DateTime.Now.Year.ToString() : DateTime.Now.Year.ToString() + "/" + (DateTime.Now.Year + 1).ToString(); font = new PdfTrueTypeFont(new Font("Calibri", 12f, FontStyle.Regular)); break; case "$major": replacement = student.Major; font = new PdfTrueTypeFont(new Font("Calibri", 12f, FontStyle.Regular)); break; case "$typeofstudies": replacement = student.TypeOfStudies; font = new PdfTrueTypeFont(new Font("Calibri", 12f, FontStyle.Regular)); break; case "$semester": replacement = student.Semester.ToString(); font = new PdfTrueTypeFont(new Font("Calibri", 12f, FontStyle.Regular)); break; case "$labdate": replacement = details.LabDate.ToString(); font = new PdfTrueTypeFont(new Font("Calibri", 12f, FontStyle.Regular)); break; case "$group": replacement = student.Group.ToString(); font = new PdfTrueTypeFont(new Font("Calibri", 12f, FontStyle.Regular)); break; case "$section": replacement = student.Section.ToString(); font = new PdfTrueTypeFont(new Font("Calibri", 12f, FontStyle.Regular)); break; case "$deadlinedate": replacement = details.DeadlineDate.ToString("dd/MM/yy"); font = new PdfTrueTypeFont(new Font("Calibri", 12f, FontStyle.Regular)); break; case "$returneddate": replacement = DateTime.Now.ToString("dd/MM/yy"); font = new PdfTrueTypeFont(new Font("Calibri", 12f, FontStyle.Regular)); break; default: replacement = "ERROR"; font = new PdfTrueTypeFont(new Font("Calibri", 12f, FontStyle.Underline)); break; } RectangleF rec = location.Bounds; page.Canvas.DrawRectangle(PdfBrushes.White, rec); page.Canvas.DrawString(replacement, font, PdfBrushes.Black, new PointF(rec.Left, rec.Top - 3f)); } } //template.SaveToFile("C:\\Users\\Lenovo\\source\\repos\\ApiConcept\\ApiConcept\\Templates\\report.pdf"); MemoryStream stream = new MemoryStream(); template.SaveToStream(stream); return(stream); }
public ActionResult Hash(string certUserBase64 = "", string fileName = "", int LoaiChuKy = 0, int numberPage = 1) { var statusResultHashFile = "error"; var descErrorHashFile = ""; var serialNumber = ""; var hashBase64 = ""; try { if (certUserBase64 == null || certUserBase64.Trim().Length == 0) { descErrorHashFile = "Cert Chain is empty"; return(Json(new { statusResultHashFile = statusResultHashFile, descErrorHashFile = descErrorHashFile, serialNumber = "", hashBase64 = "" }, JsonRequestBehavior.AllowGet)); } if (fileName == null || fileName.Trim().Length == 0 || fileName.IndexOf(".pdf") == -1) { descErrorHashFile = "Chưa chọn File cần ký"; return(Json(new { statusResultHashFile = statusResultHashFile, descErrorHashFile = descErrorHashFile, serialNumber = "", hashBase64 = "" }, JsonRequestBehavior.AllowGet)); } //Get the servers upload directory real path name string HCC_FILE_PDF = GetUrlFileDefaut(); string fileFullPath = Path.Combine(HCC_FILE_PDF, fileName); bool exists = System.IO.File.Exists(fileFullPath); if (!exists) { descErrorHashFile = "File không tồn tại"; return(Json(new { statusResultHashFile = statusResultHashFile, descErrorHashFile = descErrorHashFile, serialNumber = "", hashBase64 = "" }, JsonRequestBehavior.AllowGet)); } string[] stringSeparators = new string[] { "," }; String[] chainBase64 = certUserBase64.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries); if (chainBase64 == null || chainBase64.Length == 0) { descErrorHashFile = "Lấy Chứng thư số không thành công"; return(Json(new { statusResultHashFile = statusResultHashFile, descErrorHashFile = descErrorHashFile, serialNumber = "", hashBase64 = "" }, JsonRequestBehavior.AllowGet)); } X509Certificate x509Cert = CertUtils.GetX509Cert(chainBase64[0]); //Check chứng thư số còn giá trị //#if DEBUG //#else // var tokenValid = x509Cert.IsValidNow; // if (tokenValid != true) // { // descErrorHashFile = "Chứng thư số đã hết hiệu lực."; // return Json(new // { // statusResultHashFile = statusResultHashFile, // descErrorHashFile = descErrorHashFile, // serialNumber = "", // hashBase64 = "" // }, JsonRequestBehavior.AllowGet); // } //#endif if (x509Cert == null) { descErrorHashFile = "Lấy Chứng thư số không thành công"; return(Json(new { statusResultHashFile = statusResultHashFile, descErrorHashFile = descErrorHashFile, serialNumber = "", hashBase64 = "" }, JsonRequestBehavior.AllowGet)); } X509Certificate certCA = null; if (chainBase64.Length > 1) { certCA = CertUtils.GetX509Cert(chainBase64[1]); } X509Certificate[] certChain = null; if (certCA != null) { certChain = new X509Certificate[] { x509Cert, certCA }; } else { string certViettelCABase64 = "MIIEKDCCAxCgAwIBAgIKYQ4N5gAAAAAAETANBgkqhkiG9w0BAQUFADB+MQswCQYDVQQGEwJWTjEzMDEGA1UEChMqTWluaXN0cnkgb2YgSW5mb3JtYXRpb24gYW5kIENvbW11bmljYXRpb25zMRswGQYDVQQLExJOYXRpb25hbCBDQSBDZW50ZXIxHTAbBgNVBAMTFE1JQyBOYXRpb25hbCBSb290IENBMB4XDTE1MTAwMjAyMzIyMFoXDTIwMTAwMjAyNDIyMFowOjELMAkGA1UEBhMCVk4xFjAUBgNVBAoTDVZpZXR0ZWwgR3JvdXAxEzARBgNVBAMTClZpZXR0ZWwtQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDLdiGZcPhwSm67IiLUWELaaol8kHF+qHPmEdcG0VDKf0FtpSWiE/t6NPzqqmoF4gbIrue1/TzUs7ZeAj28o6Lb2BllA/zB6YFrXfppD4jKqHMO139970MeTbDrhHTbVugX4t2QHS+B/p8+8lszJpuduBrnZ/LWxbhnjeQRr21g89nh/W5q1VbIvZnq4ci5m0aDiJ8arhK2CKpvNDWWQ5E0L7NTVoot8niv6/Wjz19yvUCYOKHYsq97y7eBaSYmpgJosD1VtnXqLG7x4POdb6Q073eWXQB0Sj1qJPrXtOqWsnnmzbbKMrnjsoE4gg9B6qLyQS4kRMp0RrUV0z041aUFAgMBAAGjgeswgegwCwYDVR0PBAQDAgGGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFAhg5h8bFNlIgAtep1xzJSwgDfnWMB8GA1UdIwQYMBaAFM1iceRhvf497LJAYNOBdd06rGvGMDwGA1UdHwQ1MDMwMaAvoC2GK2h0dHA6Ly9wdWJsaWMucm9vdGNhLmdvdi52bi9jcmwvbWljbnJjYS5jcmwwRwYIKwYBBQUHAQEEOzA5MDcGCCsGAQUFBzAChitodHRwOi8vcHVibGljLnJvb3RjYS5nb3Yudm4vY3J0L21pY25yY2EuY3J0MA0GCSqGSIb3DQEBBQUAA4IBAQCHtdHJXudu6HjO0571g9RmCP4b/vhK2vHNihDhWYQFuFqBymCota0kMW871sFFSlbd8xD0OWlFGUIkuMCz48WYXEOeXkju1fXYoTnzm5K4L3DV7jQa2H3wQ3VMjP4mgwPHjgciMmPkaBAR/hYyfY77I4NrB3V1KVNsznYbzbFtBO2VV77s3Jt9elzQw21bPDoXaUpfxIde+bLwPxzaEpe7KJhViBccJlAlI7pireTvgLQCBzepJJRerfp+GHj4Z6T58q+e3a9YhyZdtAHVisWYQ4mY113K1V7Z4D7gisjbxExF4UyrX5G4W0h0gXAR5UVOstv5czQyDraTmUTYtx5J"; X509Certificate certViettelCA = CertUtils.GetX509Cert(certViettelCABase64); if (certViettelCA != null) { certChain = new X509Certificate[] { x509Cert, certViettelCA }; } } if (certChain == null || certChain.Length != 2) { descErrorHashFile = "Lấy Chứng thư số không thành công. Không lấy được CTS CA."; return(View()); } String base64Hash = null; //Trước khi insert thì kiểm tra chữ ký if (LoaiChuKy == 0) { //Lấy ra các loại chữ ký var lstChuKy = (from t in _chuKyRepos.GetAll() where t.IsActive == true && t.UserId == UserSession.Id select t).ToList(); if (lstChuKy.Count == 0) { descErrorHashFile = "Người dùng chưa import chữ ký, Vui lòng import chữ ký"; return(Json(new { statusResultHashFile = statusResultHashFile, descErrorHashFile = descErrorHashFile, serialNumber = "", hashBase64 = "" }, JsonRequestBehavior.AllowGet)); } if (lstChuKy.Count > 0) { int trangky = 1; float vitrix = 0; float vitriy = 0; float widthImg = 0; float heightImg = 0; Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument(); doc.LoadFromFile(fileFullPath); PdfTextFind[] results = null; int checkChuKy = 0; for (int k = 0; k < doc.Pages.Count; k++) { PdfPageBase page = doc.Pages[k]; for (int i = 0; i < lstChuKy.Count; i++) { var machu = "ATTP_" + lstChuKy[i].MaChuKy; results = page.FindText(machu).Finds; if (results.Length > 0) { foreach (PdfTextFind text in results) { var ImageData = lstChuKy[i].DataImage; var urlImage = (Path.Combine(HCC_FILE_PDF, lstChuKy[i].UrlImage)); if (!string.IsNullOrEmpty(urlImage)) { if (!System.IO.File.Exists(urlImage)) { descErrorHashFile = "Chữ ký người dùng chưa import"; return(Json(new { statusResultHashFile = statusResultHashFile, descErrorHashFile = descErrorHashFile, serialNumber = "", hashBase64 = "" }, JsonRequestBehavior.AllowGet)); } ImageData = System.IO.File.ReadAllBytes(urlImage); } //System.Drawing.Image image = null; //using (var ms = new MemoryStream(ImageData)) //{ // image = Image.FromStream(ms); //} trangky = k + 1; vitrix = text.Position.X; vitriy = page.Size.Height - text.Position.Y - 20; widthImg = 80; heightImg = 40; if (lstChuKy[i].LoaiChuKy == (int)CommonENum.LOAI_CHU_KY.CHU_KY) { if (machu == "ATTP_CK_1_1") { widthImg = 171; heightImg = 100; vitrix = text.Position.X - 30; vitriy = page.Size.Height - text.Position.Y - 80; } else { widthImg = 80; heightImg = 40; vitriy = page.Size.Height - text.Position.Y - 20; } //điều chỉnh kích thước theo cấu hình của chữ ký if (lstChuKy[i].ChieuRong.HasValue && lstChuKy[i].ChieuRong > 0) { widthImg = lstChuKy[i].ChieuRong.Value; } if (lstChuKy[i].ChieuCao.HasValue && lstChuKy[i].ChieuCao > 0) { heightImg = lstChuKy[i].ChieuCao.Value; } } if (lstChuKy[i].LoaiChuKy == (int)CommonENum.LOAI_CHU_KY.DAU_CUA_CUC) { widthImg = 75; heightImg = 75; vitrix = text.Position.X - (widthImg / 2); vitriy = page.Size.Height - text.Position.Y - heightImg; } base64Hash = HashFilePDF.GetHashTypeImage_ExistedSignatureField(fileFullPath, certChain, k + 1, urlImage, vitrix, vitriy, widthImg, heightImg); checkChuKy = 1; } } } } if (checkChuKy == 0) { base64Hash = HashFilePDF.GetHashTypeRectangleText(1, fileFullPath, certChain); } } } else if (LoaiChuKy == 1) { base64Hash = HashFilePDF.GetHashTypeRectangleText(numberPage, fileFullPath, certChain); } else { base64Hash = HashFilePDF.GetHashTypeRectangleText(numberPage, fileFullPath, certChain); } if (base64Hash == null) { descErrorHashFile = "Tạo Hash không thành công"; return(View()); } statusResultHashFile = "success"; serialNumber = x509Cert.SerialNumber.ToString(16); hashBase64 = base64Hash; return(Json(new { statusResultHashFile = statusResultHashFile, descErrorHashFile = descErrorHashFile, serialNumber = serialNumber, hashBase64 = hashBase64 }, JsonRequestBehavior.AllowGet)); } catch (Exception) { descErrorHashFile = "Lỗi trong quá trình xử lý"; return(Json(new { statusResultHashFile = statusResultHashFile, descErrorHashFile = descErrorHashFile, serialNumber = "", hashBase64 = "" }, JsonRequestBehavior.AllowGet)); } }
//向PDF指定位置添加图片 /// <summary> /// 向PDF指定位置添加图片 /// </summary> /// <param name="filePath"></param> /// <param name="newPath"></param> /// <param name="flagTxt">标记字符串</param> /// <param name="BlobFiled">图片字符串</param> /// <param name="imgHeight">图片高度,为0时使用图片原始高度</param> /// <param name="imgWidth">图片宽度,为0时使用图片原始宽度</param> public void addImage2Pdf(string filePath, string newPath, string flagTxt, string BlobFiled, float imgWidth, float imgHeight) { try { //Create a pdf document PdfDocument doc = new PdfDocument(); doc.LoadFromFile(filePath); //get the page PdfPageBase page = doc.Pages[0]; //获取文本在PdfPage的坐标 PointF pointf = new PointF(); PdfTextFind[] result = page.FindText(flagTxt).Finds; //如果没找到标记字符串,直接返回 if (result.Length == 0) { classLims_NPOI.WriteLog("标记字符串未找到", ""); return; } //获取第一次出现文字的坐标,宽度和高度 pointf = result[0].Position; //获取文字的宽高 SizeF size = result[0].Size; byte[] numArray = System.Text.Encoding.UTF8.GetBytes(BlobFiled); if (numArray == null) { classLims_NPOI.WriteLog("字节数组为空", ""); return; } PdfImage image = PdfImage.FromStream(new MemoryStream(numArray)); float width = imgWidth; float height = imgHeight; if (imgWidth == 0) { width = image.Width; } if (imgHeight == 0) { height = image.Height; } //签名图片Y轴位置为 始终和标记字符串居中对齐 pointf.Y = pointf.Y - (height - size.Height) / 2; //insert image page.Canvas.DrawImage(image, pointf.X, pointf.Y, width, height); //save pdf file doc.SaveToFile(newPath); doc.Close(); } catch (Exception ex) { classLims_NPOI.WriteLog(ex, ""); } }
//向PDF指定位置添加图片 /// <summary> /// 向PDF指定位置添加图片,按照标记字符串 /// </summary> /// <param name="filePath"></param> /// <param name="newPath"></param> /// <param name="flagTxt">标记字符串</param> /// <param name="imgPath">图片路径</param> /// <param name="imgHeight">图片高度,为0时使用图片原始高度</param> /// <param name="imgWidth">图片宽度,为0时使用图片原始宽度</param> public void addImage2Pdf_path(string filePath, string newPath, string flagTxt, string imgPath, float imgWidth, float imgHeight) { try { //Create a pdf document PdfDocument doc = new PdfDocument(); doc.LoadFromFile(filePath); PdfPageBase page = null; PdfTextFind[] result = null; for (int i = 0; i < doc.Pages.Count; i++) { page = doc.Pages[i]; PdfTextFindCollection pdfTextFindCollection = null; //pdfTextFindCollection = page.FindText(flagTxt); //pdfTextFindCollection = page.ExecuteCommandFindText(flagTxt); pdfTextFindCollection = page.FindText(flagTxt); if (pdfTextFindCollection == null) { continue; } result = pdfTextFindCollection.Finds; if (result.Length > 0) { break; } } //如果没找到标记字符串,记录并返回 if (result == null || result.Length == 0) { classLims_NPOI.WriteLog("标记字符串未找到", ""); return; } //获取第一次出现文字的坐标,宽度和高度 PointF pointf = result[0].Position; //获取文字的宽高 SizeF size = result[0].Size; if (!File.Exists(imgPath)) { classLims_NPOI.WriteLog("图片文件未找到", ""); return; } PdfImage image = PdfImage.FromFile(imgPath); float width = imgWidth; float height = imgHeight; if (imgWidth == 0) { width = image.Width; } if (imgHeight == 0) { height = image.Height; } //签名图片Y轴位置为 始终和标记字符串居中对齐 pointf.Y = pointf.Y - (height - size.Height) / 2; //insert image page.Canvas.DrawImage(image, pointf.X, pointf.Y, width, height); //save pdf file doc.SaveToFile(newPath); doc.Close(); } catch (Exception ex) { classLims_NPOI.WriteLog(ex, ""); } }