public MemoryStream GetPdf(string html) { HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.WebKit); WebKitConverterSettings settings = new WebKitConverterSettings(); //Set WebKit path settings.WebKitPath = @"../../QtBinariesDotNetCore/"; settings.Margin = new Syncfusion.Pdf.Graphics.PdfMargins { All = 30 }; settings.PdfPageSize = new SizeF(512, 692); settings.WebKitViewPort = new Size(800, 0); //Assign WebKit settings to HTML converter htmlConverter.ConverterSettings = settings; //Convert URL to PDF PdfDocument document = htmlConverter.Convert(html, ""); string filePath = "D:\\DemoProjects\\Movers\\MoversApi\\temp\\RevisedEstimate_back.pdf"; FileStream fileStream = new FileStream(filePath, FileMode.Open); PdfLoadedDocument loadedDocument = new PdfLoadedDocument(fileStream); //Save and close the PDF document MemoryStream stream = new MemoryStream(); PdfDocumentBase.Merge(document, loadedDocument); document.Save(stream); document.Close(true); return(stream); }
private static void Merger(PdfLoadedDocument doc, object[] dobj) { if (dobj != null && dobj.Length > 0) { PdfDocumentBase.Merge(doc, dobj); } }
private void button1_Click(object sender, EventArgs e) { String[] files = new String[] { @"F:\360Downloads\22.pdf", @"F:\360Downloads\11.pdf" }; string outputFile = "result.pdf"; PdfDocumentBase doc = PdfDocument.MergeFiles(files); doc.Save(outputFile, FileFormat.PDF); //save text //PdfReader pdfReader = new PdfReader(@"F:\360Downloads\100个最著名的标题 杰亚伯拉罕.pdf"); //int numberOfPages = pdfReader.NumberOfPages; //StringBuilder text = new StringBuilder(); //for (int i = 1; i <= numberOfPages; ++i) //{ // text.Append(iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(pdfReader, i)); //} //pdfReader.Close(); //PDFOperation pdf = new PDFOperation(); //pdf.Open(new FileStream(@"F:\360Downloads\11.pdf", FileMode.Append, FileAccess.Write)); ////pdf.AddParagraph(text.ToString(), 15); //pdf.AddParagraph("测试文档(生成时间:" + DateTime.Now + ")", 15); //pdf.AddImage(@"C:\Users\Mayo\Pictures\timg.jpg",1,100,100); //pdf.Close(); }
/// <summary> /// Export to PDF on Button click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Exportbutton_Click(object sender, EventArgs e) { var converter = new GridPDFConverter(); var lowest = 0; //Adding PageBreaks to a list. var rows = new List <int> { 30, 63, 90, 130, 150 }; var pdfDocument = new PdfDocument(); pdfDocument.Save("Sample.pdf"); foreach (var rownumber in rows) { var pdf = new PdfDocument(); var maximumRow = rownumber; converter.ExportToPdf(pdf, gridControl1, GridRangeInfo.Rows(lowest, maximumRow)); var stream = new MemoryStream(); pdf.Save(stream); var loadedDocument = new PdfLoadedDocument("Sample.pdf"); loadedDocument = PdfDocumentBase.Merge(loadedDocument, new PdfLoadedDocument(stream)) as PdfLoadedDocument; loadedDocument.Save("Sample.pdf"); loadedDocument.Close(true); stream.Dispose(); lowest = maximumRow + 1; } var loadedDocument1 = new PdfLoadedDocument("Sample.pdf"); loadedDocument1.Pages.RemoveAt(0); loadedDocument1.Save("Sample.pdf"); Process.Start("Sample.pdf"); }
private void btnMerge_Click(object sender, EventArgs e) { DialogResult dr = this.saveFileDialog1.ShowDialog(); if (dr == System.Windows.Forms.DialogResult.OK) { if (!isValid()) { return; } string path = this.saveFileDialog1.InitialDirectory; var newFileName = this.saveFileDialog1.FileName; string[] files = _Files.OrderBy(o => o.Order).ThenBy(f => f.FileName).Select(x => x.Filepath).ToArray(); PdfDocumentBase doc = PdfDocument.MergeFiles(files); if (File.Exists(newFileName)) { File.Delete(newFileName); } doc.Save(newFileName, FileFormat.PDF); changeStepColor(this.btnStep3, false, Color.DarkSeaGreen, Color.White); lblSuccess.Visible = true; lblStatus.Text = "Status : Files merged and saved"; if (this.chkOpen.Checked) { Process.Start(newFileName); } } }
protected override string ExtractText(string extensionName, byte[] data) { StringBuilder stringBuilder = new StringBuilder(); PdfDocumentBase doc = null; try { using (MemoryStream memoryStream = new MemoryStream(data)) { doc = SPdfDocument.MergeFiles(new Stream[] { memoryStream }); foreach (PdfPageBase page in doc.Pages) { stringBuilder.AppendLine(page.ExtractText()); } doc.Close(); } } finally { if (doc != null) { doc.Close(); } } return(stringBuilder.ToString()); }
protected override Picture[] ExtractImages(string extensionName, byte[] data) { List <Picture> pictures = new List <Picture>(); PdfDocumentBase doc = null; try { using (MemoryStream memoryStream = new MemoryStream(data)) { doc = SPdfDocument.MergeFiles(new Stream[] { memoryStream }); foreach (PdfPageBase page in doc.Pages) { foreach (Image image in page.ExtractImages()) { pictures.Add(new Picture() { Data = GetImageData(image), Extension = ImageFormat.Jpeg.ToString(), Width = image.Width, Height = image.Height }); } } } } finally { if (doc != null) { doc.Close(); } } return(pictures.ToArray()); }
private void button1_Click(object sender, EventArgs e) { String[] files = new String[] { @"D:\Comparar\1.pdf", @"D:\Comparar\2.pdf", @"D:\Comparar\3.pdf" }; string outputFile = @"D:\Comparar\result.pdf"; PdfDocumentBase doc = PdfDocument.MergeFiles(files); doc.Save(outputFile, FileFormat.PDF); }
//method to get menu for restaurant private void PopulateMenuTab(JObject json) { if (json["Menus"].Type == JTokenType.Null || string.IsNullOrEmpty(json["Menus"].ToString()) || !json["Menus"].Any()) { pdfViewerControl.IsVisible = false; MenuLabel.Text = "No Menus Currently Available."; } else { int menuLength = json["Menus"].Count(); //Create a new PDF document PdfDocument document = new PdfDocument(); var listMenu = new List <byte[]>(); for (int i = 0; i < menuLength; i++) { //Provide the PDF document URL in the below overload. var pdfUrl = json["Menus"][i]["StorageUrl"].ToString(); try { //Returns the PDF document from the given URL var documenStream = DownloadPdfStream(pdfUrl); listMenu.Add(documenStream); } catch (WebException wex) { if (wex.Source != null) { Console.WriteLine("WebException source: {0}", wex.Source); } throw; } } PdfMergeOptions mergeOptions = new PdfMergeOptions { //Enable Optimize Resources OptimizeResources = true }; //Merge the documents PdfDocumentBase.Merge(document, mergeOptions, listMenu.ToArray()); //Save the PDF document to stream MemoryStream stream = new MemoryStream(); document.Save(stream); //Close the documents document.Close(true); pdfViewerControl.LoadDocument(stream); } }
static void Main(string[] args) { //Initialize an array,and the elements are the PDF documents that you want to merge String[] files = new String[] { "sample1.pdf", "sample2.pdf", "sample3.pdf" }; //Call MergeFiles() method to merge the files PdfDocumentBase doc = PdfDocument.MergeFiles(files); //Save the file doc.Save("Merged.pdf", FileFormat.PDF); }
private void MergePdf(string foldPath, string destPath) { string name = Path.GetFileName(foldPath); string[] files = Directory.GetFiles(foldPath); string mergePath = Path.Combine(destPath, $"{name}.pdf"); PdfDocumentBase doc = PdfDocument.MergeFiles(files); //保存文档 doc.Save(mergePath, FileFormat.PDF); }
/// <summary> /// 合并指定文件夹下所有PDF文件 /// </summary> /// <param name="foldPath">原PDF文件夹</param> /// <param name="destPath">合并保存文件夹</param> /// <returns>合并后的PDF名称</returns> public static string MergePdf(string foldPath, string destPath) { string name = Path.GetFileName(foldPath); string[] files = Directory.GetFiles(foldPath); string mergePath = Path.Combine(destPath, $"{name}.pdf"); using (PdfDocumentBase doc = PdfDocument.MergeFiles(files)) { //保存文档 doc.Save(mergePath, FileFormat.PDF); return(name); } }
/// <summary> /// 合并多个pdf /// </summary> /// <param name="fileList">要合并的pdf数组</param> /// <param name="toFile">目标文件路径</param> /// <returns></returns> public bool MergeBySpire(object[] fileList, string toFile) { try { string[] fList; fList = classLims_NPOI.dArray2String1(fileList); PdfDocumentBase doc = PdfDocument.MergeFiles(fList); doc.Save(toFile, FileFormat.PDF); return(true); } catch (Exception ex) { classLims_NPOI.WriteLog(ex, ""); return(false); } }
private void button1_Click(object sender, EventArgs e) { FileStream stream1 = File.OpenRead(@"..\..\..\..\..\..\Data\MergePdfsTemplate_1.pdf"); FileStream stream2 = File.OpenRead(@"..\..\..\..\..\..\Data\MergePdfsTemplate_2.pdf"); FileStream stream3 = File.OpenRead(@"..\..\..\..\..\..\Data\MergePdfsTemplate_3.pdf"); //Pdf document streams Stream[] streams = new Stream[] { stream1, stream2, stream3 }; //Also can merge files by filename //Merge files by stream PdfDocumentBase doc = PdfDocument.MergeFiles(streams); //Save and launch doc.Save("MergeFilesByStream_result.pdf", FileFormat.PDF); PDFDocumentViewer("MergeFilesByStream_result.pdf"); }
private void button2_Click(object sender, EventArgs e) { string ext = string.Empty; List<Stream> filesStreams = new List<Stream>(); MemoryStream ms1 = new MemoryStream(); MemoryStream ms2 = new MemoryStream(); MemoryStream ms3 = new MemoryStream(); foreach (object item in listBox1.Items) { ext = Path.GetExtension(item.ToString()); switch (ext) { case ".docx": Document doc = new Document(item.ToString()); doc.SaveToStream(ms1, Spire.Doc.FileFormat.PDF); filesStreams.Add(ms1); break; case ".pdf": filesStreams.Add(File.OpenRead(item.ToString())); break; case ".pptx": Presentation ppt = new Presentation(item.ToString(), Spire.Presentation.FileFormat.Auto); ppt.SaveToFile(ms2, Spire.Presentation.FileFormat.PDF); filesStreams.Add(ms2); break; case ".xlsx": Workbook xls = new Workbook(); xls.LoadFromFile(item.ToString()); xls.SaveToStream(ms3, Spire.Xls.FileFormat.PDF); filesStreams.Add(ms3); break; default: break; } } string outputFile = "result.pdf"; PdfDocumentBase result = PdfDocument.MergeFiles(filesStreams.ToArray()); result.Save(outputFile, Spire.Pdf.FileFormat.PDF); ms1.Close(); ms2.Close(); ms3.Close(); }
private void btnApilar_Click(object sender, EventArgs e) { if (txtRutaDir.Text != "") { string rutaDir = txtRutaDir.Text; if (Directory.Exists(rutaDir)) { string[] subDir = Directory.GetDirectories(rutaDir); progressBar1.Maximum = subDir.Length; foreach (string dir in subDir) { string[] pdfs = Directory.GetFiles(dir); string finalPDF = dir + @"PDFinal.pdf"; if (pdfs.Length != 0) { PdfDocumentBase doc = PdfDocument.MergeFiles(pdfs); doc.Save(finalPDF, FileFormat.PDF); } Console.WriteLine("Apilando en el Directorio: " + dir); progressBar1.Value += 1; } MessageBox.Show("Proceso Completado", "", MessageBoxButtons.OK); progressBar1.Value = 0; } else { MessageBox.Show("Esta ruta no existe", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("Seleccione un directorio", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static bool PrintForm2() { try { projname = _importProjectName; String[] files = new String[2 + _Form2Number + _Form3Number]; string _blankPath = System.IO.Directory.GetCurrentDirectory() + "\\blank.pdf"; string _filename = System.IO.Directory.GetCurrentDirectory() + "\\Project\\" + projname + "\\Forms\\"; if (_Form2Number == 1) { files = new String[] { _filename + "Cover.pdf", _filename + "F1.pdf", _blankPath, _filename + "F3-1.pdf" }; } else if (_Form2Number == 2 && _Form3Number == 2) { files = new String[] { _filename + "Cover.pdf", _filename + "F1.pdf", _blankPath, _blankPath, _filename + "F3-1.pdf", _filename + "F3-2.pdf" }; } else { files = new String[] { _filename + "Cover.pdf", _filename + "F1.pdf", _blankPath, _filename + "F3-1.pdf", _filename + "F3-2.pdf" }; } string outputFile = _filename + "Print.pdf"; PdfDocumentBase doc2 = PdfDocument.MergeFiles(files); doc2.Save(outputFile, FileFormat.PDF); PdfDocument doc = new PdfDocument(); doc.LoadFromFile(_filename + "Print.pdf"); doc.PrintDocument.DefaultPageSettings.PrinterSettings.Duplex = System.Drawing.Printing.Duplex.Vertical; doc.PrintDocument.Print(); doc.Close(); return(true); } catch (Exception e) { var s = e.ToString(); return(false); } }
private async void button1_Click(object sender, EventArgs e) { button1.Enabled = false; List <string> rr = default; try { DiarioDisponivel = null; label1.ForeColor = Color.Black; label2.ForeColor = Color.Black; //rr = await GetSiteSTJNum(dateTimePicker1.Value); rr = await GetSiteSTJNumCaptcha(); if (rr == null) { throw new Exception("Não existem ocorrências nesse dia."); } if (DiarioDisponivel == null) { throw new Exception("Não foi possivel pegar a data do diário."); } var DiarioDt = DateTime.ParseExact(DiarioDisponivel, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture); if (!File.Exists($"stj_dje_{ DiarioDt.ToString("yyyyMMdd")}.zip")) { using (WebClient wc = new WebClient()) { wc.DownloadProgressChanged += Wc_DownloadProgressChanged; await wc.DownloadFileTaskAsync(new Uri($"https://ww2.stj.jus.br/docs_internet/processo/dje/zip/stj_dje_{DiarioDt.ToString("yyyyMMdd")}.zip"), $"stj_dje_{DiarioDt.ToString("yyyyMMdd")}.zip"); } } //ZipFile.ExtractToDirectory("test.zip", "PDF"); await Task.Run(() => { using (ZipFile zip = new ZipFile($"stj_dje_{DiarioDt.ToString("yyyyMMdd")}.zip")) { if (!Directory.Exists("PDF")) { Directory.CreateDirectory("PDF"); } foreach (var file in new DirectoryInfo("PDF").EnumerateFiles()) { file.Delete(); } totalZip = iZip = 0; zip.ExtractProgress += Zip_ExtractProgress; zip.ExtractAll("PDF", ExtractExistingFileAction.InvokeExtractProgressEvent); updateProgressBar(tpb, 100, "Processo de Extração finalizado."); } // Merge PDF updateProgressBar(tpb, 0, "Processo de Merge Iniciado"); var pdfMerges = new List <string>(); var files = new DirectoryInfo("PDF").EnumerateFiles(); int iMerge = default; var intersect = files.ToList().Where(x => rr.Contains(Path.GetFileNameWithoutExtension(x.FullName).Split('_')[4])); foreach (var file in intersect) { pdfMerges.Add(file.FullName); updateProgressBar(tpb, Convert.ToInt32(iMerge++ / (0.01 * intersect.Count())), $"Jutando as informações {file.Name}"); } updateProgressBar(tpb, 0, $"Processando..."); using (PdfDocumentBase doc = PdfDocument.MergeFiles(pdfMerges.ToArray())) { updateProgressBar(tpb, 0, "Salvando Arquivo."); doc.Save("mergepdf.pdf", FileFormat.PDF); MessageBox.Show("Arquivo salvo com sucesso!"); updateProgressBar(tpb, 100, "Arquivo Salvo"); } }).ConfigureAwait(false); } catch (Exception ex) { MessageBox.Show(ex.Message); button1.Enabled = true; } button1.Invoke(new Action(() => { button1.Enabled = true; })); }
public void PrintTT() { Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; List <String> imagelist = new List <String>(); string directory = @"D:\";//磁盘路径 string MediaName = comboBoxMedia.SelectedItem.ToString().Replace(" ", "_").Replace("毫米", "MM").Replace("英寸", "Inches").Replace("像素", "Pixels"); try { if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting) { using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { int flag = 0; //获取当前布局管理器变量 LayoutManager acLayoutMgr = LayoutManager.Current; //获取当前布局变量 Layout acLayout = (Layout)acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForRead); //Layout acLayout = (Layout)acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForWrite); //获取当前布局的打印信息 PlotInfo acPlInfo = new PlotInfo() { Layout = acLayout.ObjectId }; //提示用户输入打印窗口的两个角点 PromptPointResult resultp = ed.GetPoint("\n指定第一个角点"); if (resultp.Status != PromptStatus.OK) { return; } Point3d basePt = resultp.Value; resultp = ed.GetCorner("指定对角点", basePt); if (resultp.Status != PromptStatus.OK) { return; } Point3d cornerPt = resultp.Value; //选择实体对象 // PromptSelectionOptions result1 = new PromptSelectionOptions(); SelectionFilter frameFilter = new SelectionFilter( new TypedValue[] { new TypedValue(0, "LWPOLYLINE"), new TypedValue(90, 4), new TypedValue(70, 1) }); PromptSelectionResult selectedFrameResult = ed.SelectWindow(basePt, cornerPt, frameFilter); // PromptSelectionResult selectedFrameResult = ed.GetSelection(result1, frameFilter); PromptSelectionResult selectedFrameResult1 = ed.SelectAll(frameFilter); if (selectedFrameResult.Status == PromptStatus.OK) { List <ObjectId> selectedObjectIds = new List <ObjectId>(selectedFrameResult.Value.GetObjectIds()); List <ObjectId> resultObjectIds = new List <ObjectId>(selectedFrameResult.Value.GetObjectIds()); RemoveInnerPLine(acTrans, ref selectedObjectIds, ref resultObjectIds); foreach (ObjectId frameId in resultObjectIds) { Polyline framePline = acTrans.GetObject(frameId, OpenMode.ForRead) as Polyline; framePline.Highlight(); } PlotSettings acPlSet = new PlotSettings(acLayout.ModelType); acPlSet.CopyFrom(acLayout); //着色打印选项,设置按线框进行打印 acPlSet.ShadePlot = PlotSettingsShadePlotType.Wireframe; PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current; //打印比例 //用户标准打印 acPlSetVdr.SetUseStandardScale(acPlSet, true); acPlSetVdr.SetStdScaleType(acPlSet, StdScaleType.ScaleToFit); //居中打印 acPlSetVdr.SetPlotCentered(acPlSet, true); //调用GetPlotStyleSheetList之后才可以使用SetCurrentStyleSheet System.Collections.Specialized.StringCollection sc = acPlSetVdr.GetPlotStyleSheetList(); //设置打印样式表 if (comboBoxStyleSheet.SelectedItem.ToString() == "无") { acPlSetVdr.SetCurrentStyleSheet(acPlSet, "acad.ctb"); } else { acPlSetVdr.SetCurrentStyleSheet(acPlSet, comboBoxStyleSheet.SelectedItem.ToString()); } //选择方向 if (radioButtonHorizontal.Checked) { //横向 acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG To PDF.pc3", MediaName); acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees090); } //竖向 if (radioButtonVertical.Checked) { acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG To PDF.pc3", MediaName);//获取打印图纸尺寸ComboxMedia acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees000); } PlotProgressDialog acPlProgDlg = new PlotProgressDialog(false, resultObjectIds.Count, true); string imagename = ""; string[] files = new string[] { }; List <string> listfile = new List <string>(); foreach (var frame in resultObjectIds) { if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } flag++; Entity ent = acTrans.GetObject(frame, OpenMode.ForRead) as Entity; imagename = string.Format("{0}-{1}.pdf", frame, flag); //imagelist.Add(directory + imagename); listfile.Add(directory + imagename); //设置是否使用打印样式 acPlSet.ShowPlotStyles = true; //设置打印区域 Extents3d extents3d = ent.GeometricExtents; Extents2d E2d = new Extents2d(extents3d.MinPoint.X, extents3d.MinPoint.Y, extents3d.MaxPoint.X, extents3d.MaxPoint.Y); acPlSetVdr.SetPlotWindowArea(acPlSet, E2d); acPlSetVdr.SetPlotType(acPlSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Window); //重载和保存打印信息 acPlInfo.OverrideSettings = acPlSet; //验证打印信息设置,看是否有误 PlotInfoValidator acPlInfoVdr = new PlotInfoValidator(); acPlInfoVdr.MediaMatchingPolicy = MatchingPolicy.MatchEnabled; acPlInfoVdr.Validate(acPlInfo); while (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting) { continue; } #region BackUpCode //保存App的原参数 short bgPlot = (short)Application.GetSystemVariable("BACKGROUNDPLOT"); //设定为前台打印,加快打印速度 Application.SetSystemVariable("BACKGROUNDPLOT", 0); PlotEngine acPlEng1 = PlotFactory.CreatePublishEngine(); // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "图片输出"); // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消输出"); //acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "输出进度"); acPlProgDlg.LowerPlotProgressRange = 0; acPlProgDlg.UpperPlotProgressRange = 100; acPlProgDlg.PlotProgressPos = 0; acPlProgDlg.OnBeginPlot(); acPlProgDlg.IsVisible = true; acPlEng1.BeginPlot(acPlProgDlg, null); acPlEng1.BeginDocument(acPlInfo, "", null, 1, true, directory + imagename); // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, string.Format("正在输出文件")); acPlProgDlg.OnBeginSheet(); acPlProgDlg.LowerSheetProgressRange = 0; acPlProgDlg.UpperSheetProgressRange = 100; acPlProgDlg.SheetProgressPos = 0; PlotPageInfo acPlPageInfo = new PlotPageInfo(); acPlEng1.BeginPage(acPlPageInfo, acPlInfo, true, null); acPlEng1.BeginGenerateGraphics(null); acPlEng1.EndGenerateGraphics(null); acPlEng1.EndPage(null); acPlProgDlg.SheetProgressPos = 100; acPlProgDlg.OnEndSheet(); acPlEng1.EndDocument(null); acPlProgDlg.PlotProgressPos = 100; acPlProgDlg.OnEndPlot(); acPlEng1.EndPlot(null); acPlEng1.Dispose(); acPlEng1.Destroy(); Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot); #endregion } files = listfile.ToArray(); PlotConfig config = PlotConfigManager.CurrentConfig; //获取去除扩展名后的文件名(不含路径) string fileName = SymbolUtilityServices.GetSymbolNameFromPathName(acDoc.Name, "dwg"); //定义保存文件对话框 PromptSaveFileOptions opt = new PromptSaveFileOptions("文件名") { //保存文件对话框的文件扩展名列表 Filter = "*" + config.DefaultFileExtension + "|*" + config.DefaultFileExtension, DialogCaption = "浏览打印文件", //保存文件对话框的标题 InitialDirectory = @"D:\", //缺省保存目录 InitialFileName = fileName + "-" + acLayout.LayoutName //缺省保存文件名 }; //根据保存对话框中用户的选择,获取保存文件名 PromptFileNameResult result = ed.GetFileNameForSave(opt); if (result.Status != PromptStatus.OK) { return; } fileName = result.StringResult; //string fileName = @"D:\输出.pdf"; PdfDocumentBase docx = PdfDocument.MergeFiles(files); docx.Save(fileName, FileFormat.PDF); System.Diagnostics.Process.Start(fileName); //保存App的原参数 short bgPlot1 = (short)Application.GetSystemVariable("BACKGROUNDPLOT"); //设定为前台打印,加快打印速度 Application.SetSystemVariable("BACKGROUNDPLOT", 0); PlotEngine acPlEng = PlotFactory.CreatePublishEngine(); acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "图片输出"); acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消输出"); acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "输出进度"); acPlProgDlg.LowerPlotProgressRange = 0; acPlProgDlg.UpperPlotProgressRange = 100; acPlProgDlg.PlotProgressPos = 0; acPlProgDlg.OnBeginPlot(); acPlProgDlg.IsVisible = true; acPlEng.BeginPlot(acPlProgDlg, null); acPlEng.BeginDocument(acPlInfo, "", null, 1, true, directory + imagename); acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, string.Format("正在输出文件")); acPlProgDlg.OnBeginSheet(); acPlProgDlg.LowerSheetProgressRange = 0; acPlProgDlg.UpperSheetProgressRange = 100; acPlProgDlg.SheetProgressPos = 0; PlotPageInfo acPlPageInfo1 = new PlotPageInfo(); acPlEng.BeginPage(acPlPageInfo1, acPlInfo, true, null); acPlEng.BeginGenerateGraphics(null); acPlEng.EndGenerateGraphics(null); acPlEng.EndPage(null); acPlProgDlg.SheetProgressPos = 100; acPlProgDlg.OnEndSheet(); acPlEng.EndDocument(null); acPlProgDlg.PlotProgressPos = 100; acPlProgDlg.OnEndPlot(); acPlEng.EndPlot(null); acPlEng.Dispose(); acPlEng.Destroy(); Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot1); acPlProgDlg.Dispose(); acPlProgDlg.Destroy(); for (int i = 0; i < files.Length; i++) { File.Delete(files[i]); } } while (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting) { continue; } //MessageBox.Show("打印完成!"); } } else { ed.WriteMessage("\n另一个打印进程正在进行中."); } } catch (System.Exception) { throw; } }
public IActionResult pdf(int id) { //Initialize HTML to PDF converter HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(); WebKitConverterSettings settings = new WebKitConverterSettings(); //Set WebKit path settings.WebKitPath = Path.Combine(hosting.ContentRootPath, "QtBinariesWindows"); //Assign WebKit settings to HTML converter htmlConverter.ConverterSettings = settings; //Convert URL to PDF Nomination mrki = _db.Nomination.Where(a => a.NominationId == id).Include(b => b.Applicant).ThenInclude(q => q.University).Include(b => b.Applicant).ThenInclude(c => c.ApplicationUser).ThenInclude(x => x.Country).FirstOrDefault(); PdfDocument pdfDocument = new PdfDocument(); //Add a page to the PDF document. PdfPage pdfPage = pdfDocument.Pages.Add(); //Create a PDF Template. PdfTemplate template = new PdfTemplate(900, 900); //Draw a rectangle on the template graphics template.Graphics.DrawRectangle(PdfBrushes.White, new Syncfusion.Drawing.RectangleF(0, 0, 900, 900)); PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12); PdfFont font2 = new PdfStandardFont(PdfFontFamily.Helvetica, 20); PdfFont font3 = new PdfStandardFont(PdfFontFamily.Helvetica, 16); PdfBrush brush = new PdfSolidBrush(Color.Black); //Draw a string using the graphics of the template. RectangleF bounds = new RectangleF(0, 0, pdfDocument.Pages[0].GetClientSize().Width, 52); //dirao PdfPageTemplateElement header = new PdfPageTemplateElement(bounds); //Load the PDF document FileStream imageStream = new FileStream("unmo_logo.png", FileMode.Open, FileAccess.Read); PdfImage image = new PdfBitmap(imageStream); //Draw the image in the header. header.Graphics.DrawImage(image, new PointF(75, 0), new SizeF(137, 52)); header.Graphics.DrawString("Nomination number " + mrki.NominationId, font2, brush, 205, 12); //Add the header at the top. pdfDocument.Template.Top = header; template.Graphics.DrawString("Full name: ", font, brush, 32, 15); template.Graphics.DrawString(mrki.Applicant.ApplicationUser.Name + " " + mrki.Applicant.ApplicationUser.Surname, font, brush, 280, 15); template.Graphics.DrawString("Account created: ", font, brush, 32, 30); template.Graphics.DrawString(mrki.Applicant.CreatedProfile.ToString(), font, brush, 280, 30); template.Graphics.DrawString("Nomination created: ", font, brush, 32, 45); template.Graphics.DrawString(mrki.CreatedNom.ToString(), font, brush, 280, 45); template.Graphics.DrawString("Nomination submitted: ", font, brush, 32, 60); template.Graphics.DrawString(mrki.FinishedTime.ToString(), font, brush, 280, 60); template.Graphics.DrawString("Information", font3, brush, 10, 87); template.Graphics.DrawString("E-mail: ", font, brush, 32, 112); template.Graphics.DrawString(mrki.Applicant.ApplicationUser.Email.ToString(), font, brush, 280, 112); template.Graphics.DrawString("Phone number: ", font, brush, 32, 127); template.Graphics.DrawString(mrki.Applicant.ApplicationUser.PhoneNumber.ToString(), font, brush, 280, 127); template.Graphics.DrawString("Nationality: ", font, brush, 32, 142); template.Graphics.DrawString(mrki.Applicant.ApplicationUser.Country.Name.ToString(), font, brush, 280, 142); template.Graphics.DrawString("Faculty: ", font, brush, 32, 157); template.Graphics.DrawString(mrki.Applicant.FacultyName.ToString(), font, brush, 280, 157); template.Graphics.DrawString("University: ", font, brush, 32, 172); template.Graphics.DrawString(mrki.Applicant.University.Name.ToString(), font, brush, 280, 172); template.Graphics.DrawString("Student/staff: ", font, brush, 32, 187); template.Graphics.DrawString(mrki.Applicant.TypeOfApplication.ToString(), font, brush, 280, 187); var path1 = ""; if (mrki.LearningAgreement != null) { path1 = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.LearningAgreement); } else if (mrki.WorkPlan != null) { path1 = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.WorkPlan); } var path2 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.CV); var pathx = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.Passport); var path3 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.EngProficiency); var path4 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.TranscriptOfRecords); var path5 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.MotivationLetter); var path6 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.ReferenceLetter); FileStream stream1 = new FileStream(path1, FileMode.Open, FileAccess.Read); FileStream stream2 = new FileStream(path2, FileMode.Open, FileAccess.Read); FileStream streamx = new FileStream(pathx, FileMode.Open, FileAccess.Read); FileStream stream3 = new FileStream(path3, FileMode.Open, FileAccess.Read); FileStream stream4 = new FileStream(path4, FileMode.Open, FileAccess.Read); FileStream stream5 = new FileStream(path5, FileMode.Open, FileAccess.Read); // Creates a PDF stream for merging Stream[] streams = { stream1, stream2, stream3, streamx, stream4, stream5 }; // Merges PDFDocument. PdfDocumentBase.Merge(pdfDocument, streams); ////Draw the template on the page graphics of the document. pdfPage.Graphics.DrawPdfTemplate(template, PointF.Empty); //Save the document into stream MemoryStream stream = new MemoryStream(); pdfDocument.Save(stream); stream.Position = 0; pdfDocument.Close(true); //Define the file name FileStreamResult nova = new FileStreamResult(stream, "nomination/pdf"); string nameOfFile = "Nomination_" + mrki.NominationId + "_" + mrki.Applicant.ApplicationUser.Name + "_" + mrki.Applicant.ApplicationUser.Surname + ".pdf"; nova.FileDownloadName = nameOfFile; return(nova); }
public IActionResult pdf(int id) { //Initialize HTML to PDF converter HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(); WebKitConverterSettings settings = new WebKitConverterSettings(); //Set WebKit path settings.WebKitPath = Path.Combine(hosting.ContentRootPath, "QtBinariesWindows"); //Assign WebKit settings to HTML converter htmlConverter.ConverterSettings = settings; //Convert URL to PDF Application mrki = _db.Application.Where(a => a.ApplicationId == id).Include(b => b.Applicant).ThenInclude(c => c.ApplicationUser).Include(d => d.Infos).ThenInclude(q => q.Citizenship).Include(e => e.HomeInstitutions).Include(f => f.Languages).Include(g => g.Contacts).ThenInclude(z => z.Country).Include(h => h.Documents).Include(i => i.Others).FirstOrDefault(); PdfDocument pdfDocument = new PdfDocument(); //Add a page to the PDF document. PdfPage pdfPage = pdfDocument.Pages.Add(); PdfPage pdfPage2 = pdfDocument.Pages.Add(); //Create a PDF Template. PdfTemplate template = new PdfTemplate(900, 900); PdfTemplate template2 = new PdfTemplate(900, 900); //Draw a rectangle on the template graphics template.Graphics.DrawRectangle(PdfBrushes.White, new Syncfusion.Drawing.RectangleF(0, 0, 900, 900)); template2.Graphics.DrawRectangle(PdfBrushes.White, new Syncfusion.Drawing.RectangleF(0, 0, 900, 900)); PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12); PdfFont font2 = new PdfStandardFont(PdfFontFamily.Helvetica, 20); PdfFont font3 = new PdfStandardFont(PdfFontFamily.Helvetica, 16); PdfBrush brush = new PdfSolidBrush(Color.Black); //Draw a string using the graphics of the template. RectangleF bounds = new RectangleF(0, 0, pdfDocument.Pages[0].GetClientSize().Width, 52); PdfPageTemplateElement header = new PdfPageTemplateElement(bounds); //Load the PDF document FileStream imageStream = new FileStream("unmo_logo.png", FileMode.Open, FileAccess.Read); PdfImage image = new PdfBitmap(imageStream); //Draw the image in the header. header.Graphics.DrawImage(image, new PointF(75, 0), new SizeF(137, 52)); header.Graphics.DrawString("Application number " + mrki.ApplicationId, font2, brush, 205, 12); //Add the header at the top. pdfDocument.Template.Top = header; template.Graphics.DrawString("About", font3, brush, 10, 17); template.Graphics.DrawString("Full name: ", font, brush, 32, 42); template.Graphics.DrawString(mrki.Applicant.ApplicationUser.Name + " " + mrki.Applicant.ApplicationUser.Surname, font, brush, 280, 42); template.Graphics.DrawString("Account created: ", font, brush, 32, 57); template.Graphics.DrawString(mrki.Applicant.CreatedProfile.ToString(), font, brush, 280, 57); template.Graphics.DrawString("Application created: ", font, brush, 32, 72); template.Graphics.DrawString(mrki.CreatedApp.ToString(), font, brush, 280, 72); template.Graphics.DrawString("Application submitted: ", font, brush, 32, 87); template.Graphics.DrawString(mrki.FinishedTime.ToString(), font, brush, 280, 87); template.Graphics.DrawString("Information", font3, brush, 10, 107); template.Graphics.DrawString("Gender: ", font, brush, 32, 132); template.Graphics.DrawString(mrki.Infos.Gender, font, brush, 280, 132); template.Graphics.DrawString("Date of birth: ", font, brush, 32, 149); template.Graphics.DrawString(mrki.Infos.DateOfBirth.ToShortDateString(), font, brush, 280, 149); template.Graphics.DrawString("Place of birth: ", font, brush, 32, 166); template.Graphics.DrawString(mrki.Infos.PlaceOfBirth.ToString(), font, brush, 280, 166); template.Graphics.DrawString("Citizenship: ", font, brush, 32, 183); template.Graphics.DrawString(mrki.Infos.Citizenship.Name.ToString(), font, brush, 280, 183); template.Graphics.DrawString("Passport number: ", font, brush, 32, 200); template.Graphics.DrawString(mrki.Infos.PassportNumber.ToString(), font, brush, 280, 200); template.Graphics.DrawString("Passport issue date: ", font, brush, 32, 217); template.Graphics.DrawString(mrki.Infos.PassportIssueDate.ToShortDateString(), font, brush, 280, 217); template.Graphics.DrawString("Passport expiry date: ", font, brush, 32, 234); template.Graphics.DrawString(mrki.Infos.PassportExpiryDate.ToShortDateString(), font, brush, 280, 234); template.Graphics.DrawString("Contacts", font3, brush, 10, 259); template.Graphics.DrawString("E-mail: ", font, brush, 32, 284); template.Graphics.DrawString(mrki.Contacts.Email.ToString(), font, brush, 280, 284); template.Graphics.DrawString("Phone number: ", font, brush, 32, 301); template.Graphics.DrawString(mrki.Contacts.Telephone.ToString(), font, brush, 280, 301); template.Graphics.DrawString("Street name: ", font, brush, 32, 318); template.Graphics.DrawString(mrki.Contacts.StreetName.ToString(), font, brush, 280, 318); template.Graphics.DrawString("City, town, village: ", font, brush, 32, 335); template.Graphics.DrawString(mrki.Contacts.PlaceName.ToString(), font, brush, 280, 335); template.Graphics.DrawString("Postal code: ", font, brush, 32, 352); template.Graphics.DrawString(mrki.Contacts.PostalCode.ToString(), font, brush, 280, 352); template.Graphics.DrawString("Country of residence: ", font, brush, 32, 369); template.Graphics.DrawString(mrki.Contacts.Country.Name.ToString(), font, brush, 280, 369); template.Graphics.DrawString("Languages", font3, brush, 10, 394); template.Graphics.DrawString("Native language: ", font, brush, 32, 419); template.Graphics.DrawString(mrki.Languages.Native.ToString(), font, brush, 280, 419); template.Graphics.DrawString("First foreign language: ", font, brush, 32, 436); string ff = mrki.Languages.ForeignFirst + " | " + mrki.Languages.ForeignFirstProficiency; template.Graphics.DrawString(ff, font, brush, 280, 436); template.Graphics.DrawString("Second foreign language: ", font, brush, 32, 453); string sf = mrki.Languages.ForeignSecond + " | " + mrki.Languages.ForeignSecondProficiency; template.Graphics.DrawString(sf, font, brush, 280, 453); template.Graphics.DrawString("Third foreign language: ", font, brush, 32, 470); string tf = mrki.Languages.ForeignThird + " | " + mrki.Languages.ForeignThirdProficiency; template.Graphics.DrawString(tf, font, brush, 280, 470); template.Graphics.DrawString("Number of foreign experiences: ", font, brush, 32, 487); template.Graphics.DrawString(mrki.Languages.ForeignExperienceNumber.ToString(), font, brush, 280, 487); template.Graphics.DrawString("Home institution", font3, brush, 10, 512); template.Graphics.DrawString("University: ", font, brush, 32, 537); template.Graphics.DrawString(mrki.HomeInstitutions.OfficialName.ToString(), font, brush, 280, 537); //template.Graphics.DrawString("Faculty: ", font, brush, 5, 335); //template.Graphics.DrawString(mrki.Applicant.FacultyName.ToString(), font, brush, 280, 335); template.Graphics.DrawString("Department name: ", font, brush, 32, 554); template.Graphics.DrawString(mrki.HomeInstitutions.DepartmentName.ToString(), font, brush, 280, 554); template.Graphics.DrawString("Study programme: ", font, brush, 32, 571); template.Graphics.DrawString(mrki.HomeInstitutions.StudyProgramme.ToString(), font, brush, 280, 571); template.Graphics.DrawString("Study cycle: ", font, brush, 32, 588); template.Graphics.DrawString(mrki.Applicant.StudyCycle, font, brush, 280, 588); template.Graphics.DrawString("Current term/year: ", font, brush, 32, 605); template.Graphics.DrawString(mrki.HomeInstitutions.CurrentTermOrYear.ToString(), font, brush, 280, 605); template.Graphics.DrawString("Coordinator full name: ", font, brush, 32, 622); template.Graphics.DrawString(mrki.HomeInstitutions.CoordinatorFullName.ToString(), font, brush, 280, 622); template.Graphics.DrawString("Coordinator e-mail: ", font, brush, 32, 639); template.Graphics.DrawString(mrki.HomeInstitutions.CoordinatorEmail.ToString(), font, brush, 280, 639); template.Graphics.DrawString("Coordinator phone number: ", font, brush, 32, 656); template.Graphics.DrawString(mrki.HomeInstitutions.CoordinatorPhoneNum.ToString(), font, brush, 280, 656); template.Graphics.DrawString("Coordinator address: ", font, brush, 32, 673); template.Graphics.DrawString(mrki.HomeInstitutions.CoordinatorAddress.ToString(), font, brush, 280, 673); template.Graphics.DrawString("Coordinator position: ", font, brush, 32, 690); template.Graphics.DrawString(mrki.HomeInstitutions.CoordinatorPosition.ToString(), font, brush, 280, 690); template2.Graphics.DrawString("Others", font3, brush, 10, 5); template2.Graphics.DrawString("Medical info: ", font, brush, 32, 30); template2.Graphics.DrawString(mrki.Others.MedicalInfo.ToString(), font, brush, 280, 30); template2.Graphics.DrawString("Additional requests: ", font, brush, 32, 47); template2.Graphics.DrawString(mrki.Others.AdditionalRequests.ToString(), font, brush, 280, 47); var path1 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.Documents.LearningAgreement); var path2 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.Documents.CV); var path3 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.Documents.EngProficiency); var path4 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.Documents.TranscriptOfRecords); var path5 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.Documents.MotivationLetter); var path6 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.Documents.ReferenceLetter); FileStream stream1 = new FileStream(path1, FileMode.Open, FileAccess.Read); FileStream stream2 = new FileStream(path2, FileMode.Open, FileAccess.Read); FileStream stream3 = new FileStream(path3, FileMode.Open, FileAccess.Read); FileStream stream4 = new FileStream(path4, FileMode.Open, FileAccess.Read); FileStream stream5 = new FileStream(path5, FileMode.Open, FileAccess.Read); //FileStream stream6 = new FileStream(path6, FileMode.Open, FileAccess.Read); // Creates a PDF stream for merging Stream[] streams = { stream1, stream2, stream3, stream4, stream5 };// stream6 }; // Merges PDFDocument. PdfDocumentBase.Merge(pdfDocument, streams); ////Draw the template on the page graphics of the document. pdfPage.Graphics.DrawPdfTemplate(template, PointF.Empty); pdfPage2.Graphics.DrawPdfTemplate(template2, PointF.Empty); //Save the document into stream MemoryStream stream = new MemoryStream(); pdfDocument.Save(stream); stream.Position = 0; pdfDocument.Close(true); //Define the file name FileStreamResult nova = new FileStreamResult(stream, "application/pdf"); string nameOfFile = "Application_" + mrki.ApplicationId + "_" + mrki.Applicant.ApplicationUser.Name + "_" + mrki.Applicant.ApplicationUser.Surname + ".pdf"; nova.FileDownloadName = nameOfFile; return(nova); }