private void PdfExtractWordAndPicture(string savePathCache, string midName)//参数:保存地址,处理过程中文件名称(不包含后缀) { #region 提取PDF中的文字 try { PdfDocument doc = new PdfDocument(); doc.LoadFromFile(savePathCache + "\\" + midName + ".pdf"); //加载文件 StringBuilder content = new StringBuilder(); foreach (PdfPageBase page in doc.Pages) { content.Append(page.ExtractText()); } System.IO.File.WriteAllText(savePathCache + "\\mid.txt", content.ToString()); Spire.Doc.Document document = new Spire.Doc.Document(); document.LoadFromFile(savePathCache + "\\mid.txt"); document.Replace(" ", "", true, true); document.Replace("Evaluation Warning : The document was created with Spire.PDF for .NET.", "", true, true); document.SaveToFile(savePathCache + "\\" + midName + ".doc", Spire.Doc.FileFormat.Doc); File.Delete(savePathCache + "\\mid.txt"); } catch (Exception) { MessageBox.Show("请填写正确的路径"); } #endregion #region 提取PDF中的图片 //创建一个PdfDocument类对象并加载PDF sample Spire.Pdf.PdfDocument mydoc = new Spire.Pdf.PdfDocument(); mydoc.LoadFromFile(savePathCache + "\\" + midName + ".pdf"); //声明一个IList类,元素为image IList <Image> images = new List <Image>(); //遍历PDF文档中诊断是否包含图片,并提取图片 foreach (PdfPageBase page in mydoc.Pages) { if (page.ExtractImages() != null) { foreach (Image image in page.ExtractImages()) { images.Add(image); } } } mydoc.Close(); //遍历提取的图片,保存并命名图片 int index = 0; foreach (Image image in images) { String imageFileName = String.Format(midName + "Image-{0}.png", index++); image.Save(savePathCache + "\\" + imageFileName, ImageFormat.Png); } #endregion }
public static byte[] SpirePDFHtmlToPDF(string html) { byte[] ret = null; //using (MemoryStream ms = new MemoryStream()) //{ // Spire.Pdf.HtmlConverter.Qt.HtmlConverter.Convert( // html, // //memory stream // ms, // //enable javascript // true, // //load timeout // 10 * 1000, // //page size // new SizeF(612, 792), // //page margins // new Spire.Pdf.Graphics.PdfMargins(0), // //load from content type // LoadHtmlType.SourceCode // ); //} using (MemoryStream ms = new MemoryStream()) { //Create a pdf document. Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument(); PdfPageSettings setting = new PdfPageSettings(); //setting.Size = new SizeF(1000, 1000); setting.Size = Spire.Pdf.PdfPageSize.A4; setting.Orientation = Spire.Pdf.PdfPageOrientation.Portrait; setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20); doc.Template.Top = GetHeader(doc, setting.Margins); //apply blank templates to other parts of page template doc.Template.Bottom = new PdfPageTemplateElement(doc.PageSettings.Size.Width, setting.Margins.Bottom); doc.Template.Left = new PdfPageTemplateElement(setting.Margins.Left, doc.PageSettings.Size.Height); doc.Template.Right = new PdfPageTemplateElement(setting.Margins.Right, doc.PageSettings.Size.Height); PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat(); htmlLayoutFormat.IsWaiting = true; Thread thread = new Thread(() => { doc.LoadFromHTML(html, true, setting, htmlLayoutFormat); }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); //Save pdf file. doc.SaveToStream(ms); doc.Close(); ret = ms.ToArray(); } return(ret); }
public static string ConvertePdfParaXps(string caminhoPdf) { string caminhoXps = caminhoPdf.Replace(".pdf", "Xps.xps"); Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument(); doc.LoadFromFile(caminhoPdf); doc.SaveToFile(caminhoXps, FileFormat.XPS); doc.Close(); return(caminhoXps); }
public MemoryStream SpireFields(Dictionary <string, string> formFields) { if (string.IsNullOrEmpty(this._location.Trim())) { return(null); } byte[] fileBytes; var doc = new Spire.Pdf.PdfDocument(); doc.LoadFromFile(this._location); var form = doc.Form as PdfFormWidget; doc.Pages[0].BackgroudOpacity = 1.0f; form.AutoNaming = false; form.NeedAppearances = true; foreach (var field in form.FieldsWidget.List) { var formField = field as PdfField; if (field is PdfTextBoxFieldWidget) { var textField = field as PdfTextBoxFieldWidget; if (formFields.ContainsKey(textField.Name)) { textField.Text = formFields[textField.Name]; } } else if (field is PdfCheckBoxWidgetFieldWidget) { var checkBoxField = field as PdfCheckBoxWidgetFieldWidget; if (formFields.ContainsKey(checkBoxField.Name)) { checkBoxField.Checked = formFields[checkBoxField.Name].ToUpper() == "TRUE" ? true : false; } } formField.Flatten = true; } using (var str = new MemoryStream()) { doc.SaveToStream(str); doc.Close(); return(str); } }
private void PdfToWord_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFile = new OpenFileDialog(); openFile.Filter = "Text Documents (.pdf)|*.pdf|All files (*.*) | *.*"; var result = openFile.ShowDialog(); if (result == true) { var path = openFile.FileName; var fileName = openFile.SafeFileName; Spire.Pdf.PdfDocument pdfDoc = new Spire.Pdf.PdfDocument(); pdfDoc.LoadFromFile(path); pdfDoc.ConvertOptions.SetPdfToDocOptions(); pdfDoc.SaveToFile(System.IO.Path.Combine(BasePath, $"{fileName}.doc"), Spire.Pdf.FileFormat.DOC); pdfDoc.Close(); pdfDoc.Dispose(); } }
//文档地址 https://www.e-iceblue.cn/spirepdfnet/spire-pdf-for-net-program-guide-content.html /// <summary> /// Spire插件添加二维码到PDF /// </summary> /// <param name="sourcePdf">pdf文件路径</param> /// <param name="sourceImg">二维码图片路径</param> public static void AddQrCodeToPdf(string sourcePdf, string sourceImg) { //初始化PdfDocument实例,导入PDF文件 Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument(); //加载现有文档 doc.LoadFromFile(sourcePdf); //添加一个空白页,目的为了删除jar包添加的水印,后面再移除这一页 (没有用) //PdfPageBase pb = doc.Pages.Add(); //获取第二页 //PdfPageBase page = doc.Pages[1]; //获取第1页 PdfPageBase page = doc.Pages[0]; //加载图片到Image对象 Image image = Image.FromFile(sourceImg); //调整图片大小 int width = image.Width; int height = image.Height; float scale = 0.18f; //缩放比例0.18f; Size size = new Size((int)(width * scale), (int)(height * scale)); Bitmap scaledImage = new Bitmap(image, size); //加载缩放后的图片到PdfImage对象 Spire.Pdf.Graphics.PdfImage pdfImage = Spire.Pdf.Graphics.PdfImage.FromImage(scaledImage); //设置图片位置 float x = 516f; float y = 8f; //在指定位置绘入图片 //page.Canvas.DrawImage(pdfImage, x, y); page.Canvas.DrawImage(pdfImage, new PointF(x, y), size); //移除第一个页 //doc.Pages.Remove(pb); //去除第一页水印 //保存文档 doc.SaveToFile(@sourcePdf); doc.Close(); //释放图片资源 image.Dispose(); }
public ActionResult getModel(FormModel postedModel) { RootObject MODELFROMDATABASE = new RootObject(); PDFModel PDFmdoel = new PDFModel() { DuraionTime = postedModel.formfillingtime, OperatorID = postedModel.phone, hospitalName = GlobalVariables.name, timestamp = postedModel.timestamp, PDFTitle = postedModel.title, catID = postedModel.catID, }; if (GlobalVariables.address == "" || GlobalVariables.address == null) { string json = ""; using (var client = new WebClient()) { json = client.DownloadString("http://www.supectco.com/webs/GDP/Admin/getHospitalDetail.php?active=true"); HospitalRoot log = JsonConvert.DeserializeObject <HospitalRoot>(json); GlobalVariables.address = log.hospitalDetail.First().address; GlobalVariables.name = log.hospitalDetail.First().name; GlobalVariables.mohandes = log.hospitalDetail.First().mohandes; GlobalVariables.ostan = log.hospitalDetail.First().ostan; GlobalVariables.sharestan = log.hospitalDetail.First().sharestan; GlobalVariables.phone = log.hospitalDetail.First().phone; } } //if(GlobalVariables.modelList != "") //{ //} using (var client = new WebClient()) { GlobalVariables.modelList = client.DownloadString("http://www.supectco.com/webs/GDP/Admin/getListOfFeaterForApp.php?CatID=1"); } try { string json3 = ""; using (var client = new WebClient()) { json3 = client.DownloadString("http://www.supectco.com/webs/GDP/Admin/getLastPDFName.php?name=" + postedModel.title); } if (json3.Length > 1) { List <string> firstList = json3.Split(',').ToList(); List <string> TagIds = firstList[0].Split('_').ToList(); if (TagIds.Count() > 1) { postedModel.title = postedModel.title + "_" + (int.Parse(TagIds[1]) + 1).ToString(); } else { postedModel.title = postedModel.title + "_1"; } PDFmdoel.referer = firstList[1]; PDFmdoel.PDFTitle = postedModel.title; } } catch (Exception e) { System.IO.File.WriteAllText(e.Message, postedModel.title); } //string txtpath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sample.txt"); //System.IO.File.AppendAllText(txtpath, String.Empty); System.IO.File.WriteAllText(txtpath, postedModel.title); string id = ""; try { MODELFROMDATABASE = JsonConvert.DeserializeObject <RootObject>(GlobalVariables.modelList); System.IO.File.AppendAllText(txtpath, " " + MODELFROMDATABASE.featurDataDetail.Count().ToString()); string srt = postedModel.model; // string txtpath2 = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sample2.txt"); //System.IO.File.AppendAllText(txtpath, String.Empty); //System.IO.File.AppendAllText(txtpath, srt); List <model> mymodel = JsonConvert.DeserializeObject <List <model> >(srt); string count = mymodel.Count().ToString(); System.IO.File.AppendAllText(txtpath, String.Empty); System.IO.File.AppendAllText(txtpath, count); var testFile = ""; testFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PDF/pump.pdf"); string emptyNamePDF = ""; emptyNamePDF = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PDF/pumpEmpty.pdf"); //set pdf in database ; //create pdf proccess //Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument(); //doc.LoadFromFile(testFile); //PdfTextFind results = null; ////setting position for every title //PdfPageBase page; //foreach (var item in mymodel) //{ // int PAGE = Convert.ToInt32(item.page) - 1; // page = doc.Pages[PAGE]; // if (item.value != "master") // { // results = page.FindText(item.title).Finds.First(); // float width = results.Size.Width; // item.x = (results.Position.X + width).ToString(); // item.y = (results.Position.Y).ToString(); // } //} var testFile2 = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), emptyNamePDF); string newFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ResultPDF/result" + postedModel.title + ".pdf"); string finalFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ResultPDF/" + postedModel.title + ".pdf"); Spire.Pdf.PdfDocument doc2 = new Spire.Pdf.PdfDocument(); doc2.LoadFromFile(testFile2); float pageheight = 0; foreach (PdfPageBase spipage in doc2.Pages) { int index = doc2.Pages.IndexOf(spipage); if (index == 0) { mymodel.Where(x => x.page == "1" && x.title == "address").FirstOrDefault().value = GlobalVariables.address; mymodel.Where(x => x.page == "1" && x.title == "hospital name").FirstOrDefault().value = GlobalVariables.name; mymodel.Where(x => x.page == "1" && x.title == "mohandes").FirstOrDefault().value = GlobalVariables.mohandes; mymodel.Where(x => x.page == "1" && x.title == "ostan").FirstOrDefault().value = GlobalVariables.ostan; mymodel.Where(x => x.page == "1" && x.title == "shahrestan").FirstOrDefault().value = GlobalVariables.sharestan; mymodel.Where(x => x.page == "1" && x.title == "phone").FirstOrDefault().value = GlobalVariables.phone; foreach (var item in mymodel.Where(x => x.page == "1" && x.title == "mark")) { PDFmdoel.mark = PDFmdoel.mark + item.value; } foreach (var item in mymodel.Where(x => x.page == "1" && x.title == "model")) { PDFmdoel.model = PDFmdoel.model + item.value; } foreach (var item in mymodel.Where(x => x.page == "1" && x.title == "esteghrar")) { PDFmdoel.position = PDFmdoel.position + item.value; } PDFmdoel.serial = mymodel.Where(x => x.page == "1" && x.title == "serial").FirstOrDefault().value; PDFmdoel.amval = mymodel.Where(x => x.page == "1" && x.title == "amvaal").FirstOrDefault().value; if (mymodel.Where(x => x.page == "1" && x.title == "Passed").FirstOrDefault() != null) { if (mymodel.Where(x => x.page == "1" && x.title == "Passed").FirstOrDefault().value == "true") { PDFmdoel.status = "Passed"; } } if (mymodel.Where(x => x.page == "1" && x.title == "Limited").FirstOrDefault() != null) { if (mymodel.Where(x => x.page == "1" && x.title == "Limited").FirstOrDefault().value == "true") { PDFmdoel.status = "Limited"; } } if (mymodel.Where(x => x.page == "1" && x.title == "Failed").FirstOrDefault() != null) { if (mymodel.Where(x => x.page == "1" && x.title == "Failed").FirstOrDefault().value == "true") { PDFmdoel.status = "Failed"; } } System.IO.File.WriteAllText(txtpath, "enter foreach"); foreach (var item in MODELFROMDATABASE.featurDataDetail.Where(x => x.referer != "")) { model chosen = mymodel.Where(x => x.title == item.title && x.page == item.page).SingleOrDefault(); System.IO.File.AppendAllText(txtpath, " " + item.title); if (item.max == -1 && item.min != -1) { if (double.Parse(chosen.value) >= item.min) { mymodel.Where(x => x.title == item.referer).SingleOrDefault().value = "Passed"; } else { mymodel.Where(x => x.title == item.referer).SingleOrDefault().value = "Failed"; } } else if (item.max != -1 && item.min == -1) { if (double.Parse(chosen.value) <= item.max) { mymodel.Where(x => x.title == item.referer).SingleOrDefault().value = "Passed"; } else { mymodel.Where(x => x.title == item.referer).SingleOrDefault().value = "Failed"; } } else { if (double.Parse(chosen.value) >= item.min && double.Parse(chosen.value) <= item.max) { mymodel.Where(x => x.title == item.referer).SingleOrDefault().value = "Passed"; } else { mymodel.Where(x => x.title == item.referer).SingleOrDefault().value = "Failed"; } } } string flow10 = mymodel.Where(x => x.title == "flow10").FirstOrDefault().value; if (flow10 != "") { mymodel.Where(x => x.title == "error10").FirstOrDefault().value = Math.Round(((decimal.Parse(flow10) - 10) * 10), 2).ToString().Replace("-", ""); } string flow50 = mymodel.Where(x => x.title == "flow50").FirstOrDefault().value; if (flow50 != "") { mymodel.Where(x => x.title == "error50").FirstOrDefault().value = Math.Round(((decimal.Parse(flow50) - 50) * 2), 2).ToString().Replace("-", ""); } string flow100 = mymodel.Where(x => x.title == "flow100").FirstOrDefault().value; if (flow100 != "") { mymodel.Where(x => x.title == "error100").FirstOrDefault().value = Math.Round((decimal.Parse(flow100) - 100), 2).ToString().Replace("-", ""); } //ایمنی if (mymodel.Where(x => x.title == "resmonfas").FirstOrDefault().value == "Passed" && mymodel.Where(x => x.title == "class").FirstOrDefault().value != "CLASS II") { mymodel.Where(x => x.title == "monfasel").FirstOrDefault().value = Math.Round(RandomNumberBetween(0.5, 0.1), 1).ToString(); } if (mymodel.Where(x => x.title == "resmotas").FirstOrDefault().value == "Passed" && mymodel.Where(x => x.title == "class").FirstOrDefault().value != "CLASS II") { mymodel.Where(x => x.title == "motasel").FirstOrDefault().value = Math.Round(RandomNumberBetween(1.6, 0.2), 1).ToString(); } if (mymodel.Where(x => x.title == "class").FirstOrDefault().value != "CLASS II") { int adi = (int)RandomNumberBetween(4600, 4950); int pluse = (int)RandomNumberBetween(23, 47); int tak = (int)RandomNumberBetween(7200, 9700); int takpluse = (int)RandomNumberBetween(180, 280); if (mymodel.Where(x => x.title == "res12").FirstOrDefault().value == "Passed") { mymodel.Where(x => x.title == "nashti1").FirstOrDefault().value = ((int)adi).ToString(); mymodel.Where(x => x.title == "nashti2").FirstOrDefault().value = ((int)tak).ToString(); } if (mymodel.Where(x => x.title == "res34").FirstOrDefault().value == "Passed") { mymodel.Where(x => x.title == "nashti3").FirstOrDefault().value = ((int)(adi + pluse)).ToString(); mymodel.Where(x => x.title == "nashti4").FirstOrDefault().value = ((int)(tak + takpluse)).ToString(); } } int nashtiBadiAdi = (int)RandomNumberBetween(57, 83); int nashtiBadiAdiPluse = (int)RandomNumberBetween(1, 7); int nashtiBaditak = (int)RandomNumberBetween(280, 470); int nashtiBaditakPluse = (int)RandomNumberBetween(10, 15); int badane2 = (int)nashtiBaditak; int badane3 = badane2 + 3; int badane5 = (int)nashtiBaditak + (int)nashtiBaditakPluse; int badane6 = badane5 + 3; if (mymodel.Where(x => x.title == "res123" && x.page == "4").FirstOrDefault().value == "Passed") { mymodel.Where(x => x.title == "badane1").FirstOrDefault().value = ((int)nashtiBadiAdi + (int)nashtiBadiAdiPluse).ToString(); mymodel.Where(x => x.title == "badane2").FirstOrDefault().value = badane2.ToString(); mymodel.Where(x => x.title == "badane3").FirstOrDefault().value = badane3.ToString(); } if (mymodel.Where(x => x.title == "res456" && x.page == "4").FirstOrDefault().value == "Passed") { mymodel.Where(x => x.title == "badane4").FirstOrDefault().value = ((int)nashtiBadiAdi + (2 * (int)nashtiBadiAdiPluse)).ToString(); mymodel.Where(x => x.title == "badane5").FirstOrDefault().value = badane5.ToString(); mymodel.Where(x => x.title == "badane6").FirstOrDefault().value = badane6.ToString(); } if (mymodel.Where(x => x.title == "res7" && x.page == "4").FirstOrDefault().value == "Passed") { mymodel.Where(x => x.title == "badane7").FirstOrDefault().value = ((int)nashtiBadiAdi).ToString(); } int nashtiBadiAdi2 = (int)RandomNumberBetween(57, 83); int nashtiBadiAdiPluse2 = (int)RandomNumberBetween(1, 7); int nashtiBaditak2 = (int)RandomNumberBetween(280, 470); int nashtiBaditakPluse2 = (int)RandomNumberBetween(10, 15); int ptp2 = (int)nashtiBaditak2; int ptp3 = ptp2 + 3; int ptp5 = (int)nashtiBaditak2 + (int)nashtiBaditakPluse2; int ptp6 = ptp5 + 3; if (mymodel.Where(x => x.title == "res123" && x.page == "5").FirstOrDefault().value == "Passed") { mymodel.Where(x => x.title == "ptp1").FirstOrDefault().value = ((int)nashtiBadiAdi2 + nashtiBadiAdiPluse2).ToString(); mymodel.Where(x => x.title == "ptp2").FirstOrDefault().value = ptp2.ToString(); mymodel.Where(x => x.title == "ptp3").FirstOrDefault().value = ptp3.ToString(); } if (mymodel.Where(x => x.title == "res456" && x.page == "5").FirstOrDefault().value == "Passed") { mymodel.Where(x => x.title == "ptp4").FirstOrDefault().value = ((int)nashtiBadiAdi2 + (2 * nashtiBadiAdiPluse2)).ToString(); mymodel.Where(x => x.title == "ptp5").FirstOrDefault().value = ptp5.ToString(); mymodel.Where(x => x.title == "ptp6").FirstOrDefault().value = ptp6.ToString(); } if (mymodel.Where(x => x.title == "res7" && x.page == "5").FirstOrDefault().value == "Passed") { mymodel.Where(x => x.title == "ptp7").FirstOrDefault().value = ((int)nashtiBadiAdi2).ToString(); } if (mymodel.Where(x => x.title == "class").FirstOrDefault().value == "CLASS II") { mymodel.Where(x => x.title == "monfasel").FirstOrDefault().value = "----"; mymodel.Where(x => x.title == "motasel").FirstOrDefault().value = "----"; mymodel.Where(x => x.title == "nashti1").FirstOrDefault().value = "----"; mymodel.Where(x => x.title == "nashti2").FirstOrDefault().value = "----"; mymodel.Where(x => x.title == "nashti3").FirstOrDefault().value = "----"; mymodel.Where(x => x.title == "nashti4").FirstOrDefault().value = "----"; mymodel.Where(x => x.title == "resmonfas").FirstOrDefault().value = "Not Checked"; mymodel.Where(x => x.title == "resmotas").FirstOrDefault().value = "Not Checked"; mymodel.Where(x => x.title == "res12").FirstOrDefault().value = "Not Checked"; mymodel.Where(x => x.title == "res34").FirstOrDefault().value = "Not Checked"; } else { if (mymodel.Where(x => x.title == "kablbargh").FirstOrDefault().value == "غیر قابل انفصال") { mymodel.Where(x => x.title == "monfasel").FirstOrDefault().value = "----"; mymodel.Where(x => x.title == "resmonfas").FirstOrDefault().value = "Not Checked"; } else { mymodel.Where(x => x.title == "motasel").FirstOrDefault().value = "----"; mymodel.Where(x => x.title == "resmotas").FirstOrDefault().value = "Not Checked"; } } } List <model> pageFieldes = mymodel.Where(x => x.page == (index + 1).ToString()).ToList(); pageheight = spipage.Size.Height; foreach (var item in pageFieldes) { PdfTrueTypeFont Arial = new PdfTrueTypeFont(new System.Drawing.Font("Arial", 10f), true); PdfTrueTypeFont Arial9 = new PdfTrueTypeFont(new System.Drawing.Font("Arial", 9f), true); Spire.Pdf.Graphics.PdfFont font1 = new Spire.Pdf.Graphics.PdfFont(PdfFontFamily.TimesRoman, 9); Spire.Pdf.Graphics.PdfBrush brush = PdfBrushes.Black; PdfStringFormat format = new PdfStringFormat(); SizeF size = Arial9.MeasureString(item.value, format); float Xposition = float.Parse(item.x) - size.Width; float yposition = float.Parse(item.y) - 1; PointF position = new PointF(Xposition, float.Parse(item.y)); if (item.type == 1) { if (item.value == "true") { string imagepath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "checked.png"); Spire.Pdf.Graphics.PdfImage image = Spire.Pdf.Graphics.PdfImage.FromFile(imagepath); float width = image.Width * 0.75f; float height = image.Height * 0.75f; spipage.Canvas.DrawImage(image, Xposition, yposition, 10, 10); } else { string imagepath2 = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "unchecked.png"); Spire.Pdf.Graphics.PdfImage image2 = Spire.Pdf.Graphics.PdfImage.FromFile(imagepath2); spipage.Canvas.DrawImage(image2, Xposition, yposition, 10, 10); } } else { if (item.font == "E") { spipage.Canvas.DrawString(item.value, Arial, brush, position); } else { position.X = position.X; spipage.Canvas.DrawString(item.value, Arial, brush, position, new PdfStringFormat() { RightToLeft = true }); } } } ; } doc2.SaveToFile(newFile, FileFormat.PDF); doc2.Close(); string srt2 = ""; using (PdfReader pdfReader = new PdfReader(newFile)) { float widthTo_Trim = pageheight - 15;// iTextSharp.text.Utilities.MillimetersToPoints(450); using (FileStream output = new FileStream(finalFile, FileMode.Create, FileAccess.Write)) { using (PdfStamper pdfStamper = new PdfStamper(pdfReader, output)) { iTextSharp.text.Rectangle cropBox = pdfReader.GetCropBox(1); cropBox.Top = widthTo_Trim; pdfReader.GetPageN(1).Put(PdfName.CROPBOX, new PdfRectangle(cropBox)); //for (int page = 1; page <= pdfReader.NumberOfPages; page++) //{ //} } PDFmdoel.PDFPath = finalFile; returnModel m2 = new returnModel() { status = 200, message = "http://gdp.sup-ect.ir/ResultPDF/" + postedModel.title + ".pdf", }; srt2 = JsonConvert.SerializeObject(m2); } pdfReader.Close(); setpdfindatabase(PDFmdoel); } return(Content(srt2)); } catch (Exception e) { string txtpath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sample.txt"); System.IO.File.AppendAllText(txtpath, e.Message); returnModel m = new returnModel() { status = 400, message = e.Message + id, }; string srt = JsonConvert.SerializeObject(m); return(Content(srt)); } }
public void PDFExport(object sender, RoutedEventArgs e) { Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = "Document"; dlg.DefaultExt = ".pdf"; dlg.Filter = "PDF files (*.pdf)|*.pdf"; Nullable <bool> result = dlg.ShowDialog(); if (result == true) { string data = ""; int lmsCount = 0; double tmpMax = 0; double tmpMin = 0; double tmpAvg = 0; double humMax = 0; double humMin = 0; double humAvg = 0; int ct = 0; bool first = true; Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument(); PdfPageBase page = doc.Pages.Add(); page.Canvas.DrawString("DATA REPORT", new Spire.Pdf.Graphics.PdfFont(PdfFontFamily.Helvetica, 20f), new PdfSolidBrush(new PdfRGBColor()), 300, 10); if (debut.SelectedDate.HasValue && fin.SelectedDate.HasValue && run) { List <MStatement> lms = man.GetAllStatementByDate(mainWindow.captor, debut.SelectedDate.Value, fin.SelectedDate.Value.AddDays(1)); foreach (MStatement s in lms) { data += string.Format("{0}.\t{1}\t{2}\t{3}\r\n", s.StatementId, s.DateTime, s.Temperature, s.Humidity); if (first) { tmpMin = s.Temperature; tmpMax = s.Temperature; tmpAvg = s.Temperature; humMin = s.Humidity; humMax = s.Humidity; humAvg = s.Humidity; first = false; } else { if (tmpMin > s.Temperature) { tmpMin = s.Temperature; } if (tmpMax < s.Temperature) { tmpMax = s.Temperature; } tmpAvg += s.Temperature; if (humMin > s.Humidity) { humMin = s.Humidity; } if (humMax < s.Humidity) { humMax = s.Humidity; } humAvg += s.Humidity; } ct++; } tmpAvg = tmpAvg / ct; humAvg = humAvg / ct; lmsCount = lms.Count; } else { List <MStatement> lms = man.GetAllStatement(mainWindow.captor); foreach (MStatement s in lms) { data += string.Format("{0}.\t{1}\t{2}\t{3}\r\n", s.StatementId, s.DateTime, s.Temperature, s.Humidity); if (first) { tmpMin = s.Temperature; tmpMax = s.Temperature; tmpAvg = s.Temperature; humMin = s.Humidity; humMax = s.Humidity; humAvg = s.Humidity; first = false; } else { if (tmpMin > s.Temperature) { tmpMin = s.Temperature; } if (tmpMax < s.Temperature) { tmpMax = s.Temperature; } tmpAvg += s.Temperature; if (humMin > s.Humidity) { humMin = s.Humidity; } if (humMax < s.Humidity) { humMax = s.Humidity; } humAvg += s.Humidity; } ct++; } tmpAvg = Math.Round(tmpAvg / ct, 1); humAvg = Math.Round(humAvg / ct, 1); lmsCount = lms.Count; } string info = string.Format("SN: {0}\nTotal Records: {1}\nTemp Max/Min/Avg: {2}/{3}/{4}\nHumidity Max/Min/Avg: {5}/{6}/{7}", mainWindow.captor.Serial_number, lmsCount, tmpMax, tmpMin, tmpAvg, humMax, humMin, humAvg); page.Canvas.DrawImage(); page.Canvas.DrawString(info, new Spire.Pdf.Graphics.PdfFont(PdfFontFamily.Helvetica, 12f), new PdfSolidBrush(new PdfRGBColor()), 10, 60); page.Canvas.DrawString("Temperature and humidity data", new Spire.Pdf.Graphics.PdfFont(PdfFontFamily.Helvetica, 18f), new PdfSolidBrush(new PdfRGBColor()), 10, 140); page.Canvas.DrawString(data, new Spire.Pdf.Graphics.PdfFont(PdfFontFamily.Helvetica, 12f), new PdfSolidBrush(new PdfRGBColor()), 10, 160); FileStream to_stream = new FileStream(dlg.FileName, FileMode.Create); doc.SaveToStream(to_stream); to_stream.Close(); doc.Close(); } }
private int GetZoom(string fileName) { Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument(fileName); PdfPageRotateAngle rotation = pdf.Pages[0].Rotation; double pdfPageSizeYPoint; double pdfPageSizeXPoint; switch (rotation) { case PdfPageRotateAngle.RotateAngle0: pdfPageSizeYPoint = pdf.Pages[0].Size.Height; pdfPageSizeXPoint = pdf.Pages[0].Size.Width; break; case PdfPageRotateAngle.RotateAngle90: pdfPageSizeYPoint = pdf.Pages[0].Size.Width; pdfPageSizeXPoint = pdf.Pages[0].Size.Height; break; case PdfPageRotateAngle.RotateAngle180: pdfPageSizeYPoint = pdf.Pages[0].Size.Height; pdfPageSizeXPoint = pdf.Pages[0].Size.Width; break; case PdfPageRotateAngle.RotateAngle270: pdfPageSizeYPoint = pdf.Pages[0].Size.Width; pdfPageSizeXPoint = pdf.Pages[0].Size.Height; break; default: throw new ArgumentOutOfRangeException(); } pdf.Close(); float dpiX; float dpiY; using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero)) { dpiX = graphics.DpiX; dpiY = graphics.DpiY; } double pdfPageSizeXPix = pdfPageSizeXPoint * dpiX / 72; double pdfPageSizeYPix = pdfPageSizeYPoint * dpiY / 72; int pdfViewerSizeYPix = pdfDocumentViewer.Height; int pdfViewerSizeXPix = pdfDocumentViewer.Width; double scaleX = pdfViewerSizeXPix / pdfPageSizeXPix * 100 - 0.5; double scaleY = pdfViewerSizeYPix / pdfPageSizeYPix * 100 - 0.5; return(scaleX < scaleY ? (int)scaleX : (int)scaleY); }