/// <summary> /// Converts binary to blob pointer /// </summary> /// <param name="category">The file category.</param> /// <param name="data">The data.</param> /// <param name="name">The name.</param> /// <returns>Blob Pointer</returns> public static string ConvertToFile(string category, string name, byte[] data) { if (data == null) { return null; } using (Stream stream = new MemoryStream(data)) { // convert doc, xls -> docx, xlsx Stream streamToSave = new MemoryStream(); if (FileTypeDetector.IsDoc(data)) { Aspose.Words.Document doc = new Aspose.Words.Document(stream); doc.RemoveMacros(); doc.Save(streamToSave, Aspose.Words.SaveFormat.Docx); } else if (FileTypeDetector.IsXls(data)) { Aspose.Cells.Workbook xls = new Aspose.Cells.Workbook(stream); xls.RemoveMacro(); xls.Save(streamToSave, Aspose.Cells.SaveFormat.Xlsx); } else { streamToSave = stream; } // save to file streamToSave.Position = 0; string result = BlobStoreProvider.Instance.PutBlob(category, name, streamToSave); return result; } }
public void SetLogo() { Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.doc"); //ExStart //ExFor:SwfSaveOptions.#ctor //ExFor:SwfSaveOptions //ExFor:SwfSaveOptions.LogoImageBytes //ExFor:SwfSaveOptions.LogoLink //ExSummary:Shows how to specify a custom logo and link it to a web address in the embedded document viewer. // Create an instance of SwfSaveOptions. SwfSaveOptions options = new SwfSaveOptions(); // Read the image into byte array. byte[] logoBytes = File.ReadAllBytes(MyDir + "LogoSmall.png"); // Specify the logo image to use. options.LogoImageBytes = logoBytes; // You can specify the URL of web page that should be opened when you click on the logo. options.LogoLink = "http://www.aspose.com"; //ExEnd doc.Save(MyDir + "SwfSaveOptions.CustomLogo Out.swf", options); }
public void AddEx() { //ExStart //ExFor:TabStopCollection.Add(TabStop) //ExFor:TabStopCollection.Add(Double, TabAlignment, TabLeader) //ExSummary:Shows how to create tab stops and add them to a document. Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.doc"); Aspose.Words.Paragraph paragraph = (Aspose.Words.Paragraph)doc.GetChild(Aspose.Words.NodeType.Paragraph, 0, true); // Create a TabStop object and add it to the document. Aspose.Words.TabStop tabStop = new Aspose.Words.TabStop(Aspose.Words.ConvertUtil.InchToPoint(3), Aspose.Words.TabAlignment.Left, Aspose.Words.TabLeader.Dashes); paragraph.ParagraphFormat.TabStops.Add(tabStop); // Add a tab stop without explicitly creating new TabStop objects. paragraph.ParagraphFormat.TabStops.Add(Aspose.Words.ConvertUtil.MillimeterToPoint(100), Aspose.Words.TabAlignment.Left, Aspose.Words.TabLeader.Dashes); // Add tab stops at 5 cm to all paragraphs. foreach (Aspose.Words.Paragraph para in doc.GetChildNodes(Aspose.Words.NodeType.Paragraph, true)) { para.ParagraphFormat.TabStops.Add(Aspose.Words.ConvertUtil.MillimeterToPoint(50), Aspose.Words.TabAlignment.Left, Aspose.Words.TabLeader.Dashes); } doc.Save(ExDir + "Document.AddedTabStops Out.doc"); //ExEnd }
public static void Main(string[] args) { try { // Sample infrastructure. string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar; string dataDir = new Uri(new Uri(exeDir), @"../Data/").LocalPath; //ExStart //ExId:XpsPrint_Main //ExSummary:Invoke the utility class to print via XPS. // Open a sample document in Aspose.Words. Aspose.Words.Document document = new Aspose.Words.Document(dataDir + "Print via XPS API.doc"); // Specify the name of the printer you want to print to. const string printerName = @"\\COMPANY\Zeeshan MFC-885CW Printer"; // Print the document. XpsPrintHelper.Print(document, printerName, "test", true); //ExEnd Console.WriteLine("Printed successfully."); } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("Press Enter."); Console.ReadLine(); }
private static void ConvertDoc2Pdf(string inFileName, string outFileName) { // You can load not only DOC here, but any format supported by // Aspose.Words: DOC, DOCX, RTF, WordML, HTML, MHTML, ODT etc. Aspose.Words.Document doc = new Aspose.Words.Document(inFileName); doc.Save(outFileName, new PdfSaveOptions()); }
private void SetupTemplate(object sender, EventArgs e) { if (checkBoxX1.Checked) { Template = new Aspose.Words.Document(new MemoryStream(Properties.Resources.人學期成績單樣板_高中_)); this.SubjectLimit = 25; } }
/// <summary> /// Word 转成 pdf 文件 /// </summary> /// <returns>错误信息,null 代表正常</returns> override protected string WordToPDF() { string result = null; Aspose.Words.Document doc = new Aspose.Words.Document(this._officeFileName); doc.Save(this._pdfFileName); return(result); }
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { #region 儲存檔案 string inputReportName = "個人評量成績單合併欄位總表.doc"; string reportName = inputReportName; string path = Path.Combine(System.Windows.Forms.Application.StartupPath, "Reports"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path = Path.Combine(path, reportName + ".doc"); if (File.Exists(path)) { int i = 1; while (true) { string newPath = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + (i++) + Path.GetExtension(path); if (!File.Exists(newPath)) { path = newPath; break; } } } try { //document.Save(path, Aspose.Words.SaveFormat.Doc); System.IO.FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write); stream.Write(Properties.Resources.歡樂的合併欄位總表, 0, Properties.Resources.歡樂的合併欄位總表.Length); stream.Flush(); stream.Close(); System.Diagnostics.Process.Start(path); } catch { System.Windows.Forms.SaveFileDialog sd = new System.Windows.Forms.SaveFileDialog(); sd.Title = "另存新檔"; sd.FileName = reportName + ".doc"; sd.Filter = "Word檔案 (*.doc)|*.doc|所有檔案 (*.*)|*.*"; if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { Aspose.Words.Document doc = new Aspose.Words.Document(new MemoryStream(Properties.Resources.歡樂的合併欄位總表)); doc.Save(sd.FileName, Aspose.Words.SaveFormat.Doc); } catch { FISCA.Presentation.Controls.MsgBox.Show("指定路徑無法存取。", "建立檔案失敗", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); return; } } } #endregion }
public void BuiltInPropertiesDirectAccess() { //ExStart //ExFor:BuiltInDocumentProperties.Author //ExFor:BuiltInDocumentProperties.Bytes //ExFor:BuiltInDocumentProperties.Category //ExFor:BuiltInDocumentProperties.Characters //ExFor:BuiltInDocumentProperties.CharactersWithSpaces //ExFor:BuiltInDocumentProperties.Comments //ExFor:BuiltInDocumentProperties.Company //ExFor:BuiltInDocumentProperties.CreatedTime //ExFor:BuiltInDocumentProperties.Keywords //ExFor:BuiltInDocumentProperties.LastPrinted //ExFor:BuiltInDocumentProperties.LastSavedBy //ExFor:BuiltInDocumentProperties.LastSavedTime //ExFor:BuiltInDocumentProperties.Lines //ExFor:BuiltInDocumentProperties.Manager //ExFor:BuiltInDocumentProperties.NameOfApplication //ExFor:BuiltInDocumentProperties.Pages //ExFor:BuiltInDocumentProperties.Paragraphs //ExFor:BuiltInDocumentProperties.RevisionNumber //ExFor:BuiltInDocumentProperties.Subject //ExFor:BuiltInDocumentProperties.Template //ExFor:BuiltInDocumentProperties.Title //ExFor:BuiltInDocumentProperties.TotalEditingTime //ExFor:BuiltInDocumentProperties.Version //ExFor:BuiltInDocumentProperties.Words //ExSummary:Retrieves information from the built-in document properties. string fileName = ExDir + "Properties.doc"; Aspose.Words.Document doc = new Aspose.Words.Document(fileName); Console.WriteLine("Document name: {0}", fileName); Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author); Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes); Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category); Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters); Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces); Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments); Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company); Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime); Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords); Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted); Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy); Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime); Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines); Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager); Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication); Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages); Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs); Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber); Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject); Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template); Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title); Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime); Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version); Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words); //ExEnd }
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Cancelled) { this.Close(); return; } FISCA.Presentation.MotherForm.SetStatusBarMessage("補考公告(" + _printMode + ")產生完成。"); Aspose.Words.Document doc = (Aspose.Words.Document)e.Result; doc.MailMerge.DeleteFields(); // 電子報表功能先暫時不製做 #region 電子報表 //// 檢查是否上傳電子報表 //if (chkUploadEPaper.Checked) //{ // List<Document> docList = new List<Document>(); // foreach (Section ss in doc.Sections) // { // Document dc = new Document(); // dc.Sections.Clear(); // dc.Sections.Add(dc.ImportNode(ss, true)); // docList.Add(dc); // } // Update_ePaper up = new Update_ePaper(docList, "超額比序項目積分證明單", PrefixStudent.系統編號); // if (up.ShowDialog() == System.Windows.Forms.DialogResult.Yes) // { // MsgBox.Show("電子報表已上傳!!"); // } // else // { // MsgBox.Show("已取消!!"); // } //} #endregion SaveFileDialog sd = new SaveFileDialog(); sd.Title = "另存新檔"; sd.FileName = "補考公告(" + _printMode + ").docx"; sd.Filter = "Word檔案 (*.docx)|*.docx|所有檔案 (*.*)|*.*"; if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { doc.Save(sd.FileName, Aspose.Words.SaveFormat.Docx); System.Diagnostics.Process.Start(sd.FileName); } catch { MessageBox.Show("檔案儲存失敗"); } } this.Close(); }
public ActionResult DocumentExportFilePdf(string contractId) { string name = "Счет на оплату.pdf"; StiReport report = new StiReport(); try { report.Load(Server.MapPath("~/Reports/Mrts/OBK/1c/ObkInvoicePayment.mrt")); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } report.Dictionary.Variables["ContractId"].ValueObject = contractId; //итого var totalPriceWithCount = payRepo.GetTotalPriceCount(Guid.Parse(contractId)); report.Dictionary.Variables["TotalPriceWithCount"].ValueObject = totalPriceWithCount; //в том числе НДС var totalPriceNDS = payRepo.GetTotalPriceNDS(totalPriceWithCount); report.Dictionary.Variables["TotalPriceNDS"].ValueObject = totalPriceNDS; //прописью var priceText = RuDateAndMoneyConverter.CurrencyToTxtTenge(Convert.ToDouble(totalPriceWithCount), false); report.Dictionary.Variables["TotalPriceWithCountName"].ValueObject = priceText; report.Dictionary.Variables["ChiefAccountant"].ValueObject = null; //payRepo.GetEmpoloyee(Guid.Parse("E1EE3658-0C35-41EB-99FD-FDDC4D07CEC4"))?.ShortName; report.Dictionary.Variables["Executor"].ValueObject = null; //payRepo.GetEmpoloyee(Guid.Parse("55377FAC-A5F0-4093-BBB6-18BD28E53BE1"))?.ShortName; report.Render(false); } catch (Exception ex) { LogHelper.Log.Error("ex: " + ex.Message + " \r\nstack: " + ex.StackTrace); } var stream = new MemoryStream(); var directionToPayment = payRepo.GetDirectionToPayments(Guid.Parse(contractId)); var signPayment = payRepo.GetDirectionSignData(directionToPayment.Id); if (signPayment.ChiefAccountantSign != null && signPayment.ExecutorSign != null) { try { report.ExportDocument(StiExportFormat.Word2007, stream); stream.Position = 0; Aspose.Words.Document doc = new Aspose.Words.Document(stream); doc.InserQrCodesToEnd("ChiefAccountantSign", signPayment.ChiefAccountantSign); var pdfFile = new MemoryStream(); doc.Save(pdfFile, Aspose.Words.SaveFormat.Pdf); pdfFile.Position = 0; stream.Close(); return(File(pdfFile, "application/pdf", name)); } catch (Exception e) { Console.WriteLine(e); } } report.ExportDocument(StiExportFormat.Pdf, stream); stream.Position = 0; return(File(stream, "application/pdf", name)); }
private void btnInHoaDon_Click(object sender, EventArgs e) { string dir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName; string template = dir + @"\Template\NhapKho.docx"; DataTable dt = new DataTable(); dt.Columns.Add("ngay"); dt.Columns.Add("thang"); dt.Columns.Add("nam"); dt.Columns.Add("ID"); dt.Columns.Add("NHACUNGCAP"); dt.Columns.Add("Tongtien"); NHAPHANG nh = nhDAO.getNhapHangById(idNewNH); NHACUNGCAP ncc = nccDAO.getListNCC().FirstOrDefault(x => x.ID == nh.NHACC_ID); dt.Rows.Add(new Object[] { DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year, nh.ID, ncc.TEN, String.Format("{0:0,0}", nh.TONGTIEN) }); dt.TableName = "phieu"; List <InFoCTNhapHang> lstCTNH = nhDAO.getListCTNhapHangByIdNH(idNewNH); DataTable dt2 = new DataTable(); dt2.Columns.Add("SANPHAM"); dt2.Columns.Add("HANGSX"); dt2.Columns.Add("KHOILUONG"); dt2.Columns.Add("SOLUONG"); dt2.Columns.Add("GIANHAP"); foreach (InFoCTNhapHang o in lstCTNH) { dt2.Rows.Add(new Object[] { o.SANPHAM, o.HANGSX, o.KHOILUONG, o.SOLUONGNHAP, String.Format("{0:0,0}", o.GIANHAP) }); } dt2.TableName = "chitiet"; DataSet ds = new DataSet(); ds.Tables.Add(dt); ds.Tables.Add(dt2); Aspose.Words.Document doc = new Aspose.Words.Document(template); doc.MailMerge.ExecuteWithRegions(ds); string filePath = dir + String.Format("/NhapKho_{0}.pdf", DateTime.Now.Day + "_" + DateTime.Now.Month + "_" + DateTime.Now.Year); doc.Save(filePath, Aspose.Words.SaveFormat.Pdf); Process.Start(filePath); }
public void ToStringEx() { //ExStart //ExFor:DigitalSignature.ToString //ExSummary:Shows how to use ToString. Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.Signed.docx"); Console.WriteLine(doc.DigitalSignatures[0].ToString()); //ExEnd }
private static void GenerateWordPreview(int previewsFolderId, Stream docStream) { var document = new Aspose.Words.Document(docStream); var pc = document.BuiltInDocumentProperties.Pages; // double-check if (pc == 0) { pc = document.PageCount; } //save the document only if this is the first round if (StartIndex == 0 || pc < 1) { SetPageCount(pc); } var firstIndex = 0; var lastIndex = 0; if (pc > 0) { SetIndexes(StartIndex, pc, out firstIndex, out lastIndex, MaxPreviewCount); for (var i = firstIndex; i <= lastIndex; i++) { //TODO: compare original file timestamp with current timestamp //if (!CheckActuality(file)) // break; try { using (var imgStream = new MemoryStream()) { var options = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Png) { PageIndex = i, Resolution = 300 }; document.Save(imgStream, options); if (imgStream.Length == 0) { continue; } SavePreviewAndThumbnail(imgStream, i + 1, previewsFolderId); } } catch (Exception ex) { Logger.WriteError(ContentId, i + 1, ex: ex, startIndex: StartIndex, version: Version); SaveEmptyPreview(i + 1, previewsFolderId); } } } }
public ActionResult GetContractTemplatePdf(Guid id) { var db = new ncelsEntities(); string name = "Договор_на_проведение_оценки_безопасности_и_качества.pdf"; StiReport report = new StiReport(); try { report.Load(obkRepo.GetContractTemplatePath(id));//(Server.MapPath("~/Reports/Mrts/OBK/ObkContractDec.mrt")); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } report.Dictionary.Variables["ContractId"].ValueObject = id; var price = new OBKContractRepository().GetPriceCount(id); report.Dictionary.Variables["PriceCount"].ValueObject = price; var priceText = RuDateAndMoneyConverter.ToTextTenge(Convert.ToDouble(price), false); report.Dictionary.Variables["PriceCountName"].ValueObject = priceText; report.Render(false); } catch (Exception ex) { LogHelper.Log.Error("ex: " + ex.Message + " \r\nstack: " + ex.StackTrace); } Stream stream = new MemoryStream(); report.ExportDocument(StiExportFormat.Word2007, stream); stream.Position = 0; Aspose.Words.Document doc = new Aspose.Words.Document(stream); try { var signData = db.OBK_ContractSignedDatas.Where(x => x.ContractId == id).FirstOrDefault(); if (signData != null && signData.ApplicantSign != null && signData.CeoSign != null) { doc.InserQrCodesToEnd("ApplicantSign", signData.ApplicantSign); doc.InserQrCodesToEnd("CeoSign", signData.CeoSign); } } catch (Exception ex) { } var file = new MemoryStream(); doc.Save(file, Aspose.Words.SaveFormat.Pdf); file.Position = 0; //return new FileStreamResult(stream, "application/pdf"); return(File(file, "application/pdf", name)); }
public byte[] ToPdf(string fileName) { var doc = new Aspose.Words.Document(fileName); using (var ms = new MemoryStream()) { doc.Save(ms, Aspose.Words.SaveFormat.Pdf); return(ms.ToArray()); } }
private void btnPrint_Click(object sender, EventArgs e) { List <CHITIETDONHANG> lstCTDH = dhDAO.GetCTDH(dh.ID); List <THONGTINCHITIETDH2> lstTTCT = new List <THONGTINCHITIETDH2>(); foreach (CHITIETDONHANG c in lstCTDH) { THONGTINCHITIETDH2 t2 = new THONGTINCHITIETDH2(); SANPHAM s = new SanphamDAO().getSanphamById(c.SANPHAM_ID); THONGTINCHITIETDH t = new THONGTINCHITIETDH(c, s); t2.ID = t.ID; t2.KHOILUONG = t.KHOILUONG; t2.SOLUONG = t.SOLUONG; t2.DONGIA = String.Format("{0:0,0}", t.DONGIA); t2.THANHTIEN = String.Format("{0:0,0}", t.THANHTIEN); t2.TEN = new LoaiSpDAO().getLOAISPById(t.LOAISP).TEN; lstTTCT.Add(t2); } //FormPrint formPrint = new FormPrint(lstTTCT, dh); //formPrint.ShowDialog(); string dir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName; string template = dir + @"\Template\DonHang.docx"; DataTable dt = new DataTable(); dt.Columns.Add("ngay"); dt.Columns.Add("thang"); dt.Columns.Add("nam"); dt.Columns.Add("NGUOINHAN"); dt.Columns.Add("SDT"); dt.Columns.Add("DIACHI"); dt.Columns.Add("NGAYDAT"); dt.Columns.Add("TONGTIEN"); dt.Rows.Add(new Object[] { DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year, dh.TENNGUOINHAN, dh.SDT, dh.DIACHI, String.Format("{0:dd-MM-yyyy}", dh.NGAYDAT), String.Format("{0:0,0}", dh.TONGTIEN) }); dt.TableName = "donhang"; DataTable dt2 = new ConnectAPI().ConvertToDataTable <THONGTINCHITIETDH2>(lstTTCT); dt2.TableName = "chitiet"; DataSet ds = new DataSet(); ds.Tables.Add(dt); ds.Tables.Add(dt2); Aspose.Words.Document doc = new Aspose.Words.Document(template); doc.MailMerge.ExecuteWithRegions(ds); string filePath = dir + String.Format("/DonHang_{0}_{1}.pdf", dh.TENNGUOINHAN, DateTime.Now.Day + "_" + DateTime.Now.Month + "_" + DateTime.Now.Year); doc.Save(filePath, Aspose.Words.SaveFormat.Pdf); Process.Start(filePath); }
public int SearchAndReplace(string search, string replace) { _Document doc = new _Document(dir + FileId); int result = doc.Range.Replace(search, replace, false, true); doc.Save(dir + FileId); //doc.Save(teamlabDir + FileId); return(result); }
public void ToStringEx() { //ExStart //ExFor:DigitalSignature.ToString //ExSummary:Shows how to get the string representation of a signature from a signed document. Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.Signed.docx"); Console.WriteLine(doc.DigitalSignatures[0].ToString()); //ExEnd }
///<Summary> /// ConvertDocToImageFiles method to convert doc file to image files ///</Summary> public Response ConvertDocToImageFiles(string fileName, string folderName, string outputType) { if (outputType.Equals("bmp") || outputType.Equals("jpg") || outputType.Equals("png")) { Aspose.Words.SaveFormat format = Aspose.Words.SaveFormat.Bmp; if (outputType.Equals("jpg")) { format = Aspose.Words.SaveFormat.Jpeg; } else if (outputType.Equals("gif")) { format = Aspose.Words.SaveFormat.Gif; } else if (outputType.Equals("png")) { format = Aspose.Words.SaveFormat.Png; } return(ProcessTask(fileName, folderName, "." + outputType, true, true, delegate(string inFilePath, string outPath, string zipOutFolder) { Aspose.Words.Document doc = new Aspose.Words.Document(inFilePath); ImageSaveOptions options = new ImageSaveOptions(format); options.PageCount = 1; string outfileName = ""; if (doc.PageCount > 1) { outfileName = Path.GetFileNameWithoutExtension(fileName) + "_{0}"; for (int i = 0; i < doc.PageCount; i++) { outPath = zipOutFolder + "/" + outfileName; options.PageIndex = i; doc.Save(string.Format(outPath, (i + 1) + "." + outputType), options); } } else { outfileName = Path.GetFileNameWithoutExtension(fileName); outPath = zipOutFolder + "/" + outfileName; options.PageIndex = 0; doc.Save(outPath + "." + outputType, options); } })); } return(new Response { FileName = null, Status = "Output type not found", StatusCode = 500 }); }
/// <summary> /// формирование печатной формы /// </summary> /// <param name="id"></param> /// <returns></returns> public ActionResult ExportFilePdf(Guid id) { var db = new ncelsEntities(); var assessmentDeclaration = db.OBK_AssessmentDeclaration.FirstOrDefault(dd => dd.Id == id); var fileName = assessmentDeclaration.OBK_Ref_Type.Code == "1" ? "SafetyAssessmentDeclaration.mrt" : "SafetyAssessmentDeclaration.mrt"; string name = "Заявление на проведение оценки безопасности и качества лс.pdf"; StiReport report = new StiReport(); try { report.Load(Server.MapPath("~/Reports/Mrts/" + fileName)); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } report.Dictionary.Variables["AssessmentDeclarationId"].ValueObject = id; report.Dictionary.Variables["ExecutorSign"].ValueObject = null; report.Render(false); } catch (Exception ex) { LogHelper.Log.Error("ex: " + ex.Message + " \r\nstack: " + ex.StackTrace); } Stream stream = new MemoryStream(); var assessmentDeclarationHistory = assessmentDeclaration.OBK_AssessmentDeclarationHistory.Where(dh => dh.XmlSign != null) .OrderByDescending(dh => dh.DateCreate).FirstOrDefault(); if (assessmentDeclarationHistory != null) { try { report.ExportDocument(StiExportFormat.Word2007, stream); stream.Position = 0; Aspose.Words.Document doc = new Aspose.Words.Document(stream); doc.InserQrCodesToEnd("ExecutorSign", assessmentDeclarationHistory.XmlSign); var pdfFile = new MemoryStream(); doc.Save(pdfFile, Aspose.Words.SaveFormat.Pdf); pdfFile.Position = 0; stream.Close(); return(new FileStreamResult(pdfFile, "application/pdf")); } catch (Exception e) { Console.WriteLine(e); } } report.ExportDocument(StiExportFormat.Pdf, stream); stream.Position = 0; return(new FileStreamResult(stream, "application/pdf")); }
public ActionResult GetAdditionalContractTemplatePdf(Guid id, bool?isStream, string contractAdditionTypeCode) { var db = new ncelsEntities(); StiReport report = new StiReport(); try { report.Load(obkRepo.GetContractAdditionalTemplatePath(id, contractAdditionTypeCode.Trim()));//(Server.MapPath("~/Reports/Mrts/OBK/ObkContractDec.mrt")); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } report.Dictionary.Variables["addContractNumber"].ValueObject = id; report.Render(false); } catch (Exception ex) { LogHelper.Log.Error("ex: " + ex.Message + " \r\nstack: " + ex.StackTrace); } Stream stream = new MemoryStream(); report.ExportDocument(StiExportFormat.Word2007, stream); stream.Position = 0; Aspose.Words.Document doc = new Aspose.Words.Document(stream); try { var signData = db.OBK_ContractSignedDatas.Where(x => x.ContractId == id).FirstOrDefault(); if (signData != null && signData.ApplicantSign != null && signData.CeoSign != null) { doc.InserQrCodesToEnd("ApplicantSign", signData.ApplicantSign); doc.InserQrCodesToEnd("CeoSign", signData.CeoSign); } } catch (Exception ex) { } var file = new MemoryStream(); doc.Save(file, Aspose.Words.SaveFormat.Pdf); file.Position = 0; if (isStream != null && isStream.Value) { return(new FileStreamResult(file, "application/pdf")); } else { return(File(file, "application/pdf", "")); } }
public override bool Convert(string sourceFilePath, string targetPdfPath) { Aspose.Words.LoadOptions loadOptions = new Aspose.Words.LoadOptions(); loadOptions.Encoding = Encoding.Default; var doc = new Aspose.Words.Document(sourceFilePath, loadOptions); doc.Save(targetPdfPath, Aspose.Words.SaveFormat.Pdf); return(File.Exists(targetPdfPath) && new FileInfo(targetPdfPath).Length > 0); }
public override bool Convert(string sourceFilePath, string targetPdfPath) { var doc = new Aspose.Words.Document(sourceFilePath); Aspose.Words.Saving.PdfSaveOptions saveOptions = new Aspose.Words.Saving.PdfSaveOptions(); saveOptions.OutlineOptions.HeadingsOutlineLevels = 3; doc.Save(targetPdfPath, saveOptions); return(File.Exists(targetPdfPath) && new FileInfo(targetPdfPath).Length > 0); }
public void ToStringEx() { //ExStart //ExFor:ToString //ExId:ToStringEx //ExSummary:Shows how to use ToString. Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.Signed.docx"); Console.WriteLine(doc.DigitalSignatures[0]); //ExEnd }
private void SetupTemplate(object sender, EventArgs e) { if (checkBoxX1.Checked) { Template = new Aspose.Words.Document(new MemoryStream(Properties.Resources.人學期成績單樣板)); this.SubjectLimit = 30; this.WithSchoolYearScore = true; this.WithPrevSemesterScore = true; } }
/// <summary> /// 将给定的 word 文档(.doc|.docx)转换为 html /// </summary> /// <param name="docFileName">word 文档绝对路径</param> /// <param name="targetPath">转换后的 html 文件存储路径,若此参数为 null,则 html 文件存储路径将与 word 文档一致</param> /// <exception cref="FileNotFoundException"></exception> /// <exception cref="InvalidOperationException"></exception> /// <exception cref="Exception"></exception> public static void Word2Html(string docFileName, string targetPath = null) { if (!File.Exists(docFileName)) { throw new FileNotFoundException(); } var ext = Path.GetExtension(docFileName).ToLower(); if (ext != ".doc" && ext != ".docx") { throw new InvalidOperationException("此函数仅支持转换“.doc|.docx”格式的文件"); } if (!targetPath.IsNullOrEmpty()) { if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } } else { targetPath = Path.GetDirectoryName(docFileName); } var htmlFilename = Path.Combine(targetPath, Path.GetFileNameWithoutExtension(docFileName) + ".html"); #region Microsoft.Office.Interop.Word //var word = new ApplicationClass(); //Document doc = null; //try //{ // doc = word.Documents.Open(docFileName); // doc.SaveAs2(htmlFilename, WdSaveFormat.wdFormatHTML); //} //catch (Exception ex) //{ // throw ex; //} //finally //{ // doc?.Close(); // word.Quit(); //} #endregion // Aspose.Words var doc = new Aspose.Words.Document(docFileName); doc.Save(htmlFilename, new Aspose.Words.Saving.HtmlSaveOptions { SaveFormat = Aspose.Words.SaveFormat.Html, Encoding = Encoding.GetEncoding("GB2312") }); }
public string GenerateDocument(DocGenItem docItem) { try { _documentGeneratedItem = docItem; var fm = new FieldMerger(); //look for the temporary folder that the document will be place in //if it does not exist, create the directory string tempDirStr = documentFileName.Substring(0, documentFileName.IndexOf(CLIENT_NAME, 0) + CLIENT_NAME.Length); if (!Directory.Exists(tempDirStr)) Directory.CreateDirectory(tempDirStr); //if a document exists in the temp directory with the same name already, delete it if (File.Exists(documentFileName)) File.Delete(documentFileName); //check if the template file exists and throw an exception if it does not if (!File.Exists(templateFileName)) { throw new Exception("templateFileName (" + templateFileName + ") does not exist"); } //copy the template file, Copy() will not overwrite an existing file File.Copy(templateFileName, documentFileName); var docGenerated = new Aspose.Words.Document(documentFileName); docGenerated.MailMerge.FieldMergingCallback = new MailMergeFieldHandler(fm); var fieldNames = docGenerated.MailMerge.GetFieldNames(); if (fieldNames != null && fieldNames.Length > 0) { foreach (var fieldName in fieldNames) { var fieldValue = fm.GetMerge(fieldName); if (!string.IsNullOrEmpty(fieldValue)) { fieldValue = fieldValue.Replace(System.Environment.NewLine, Aspose.Words.ControlChar.LineBreak); } docGenerated.MailMerge.Execute(new string[] {fieldName}, new object[] {fieldValue}); } } docGenerated.Save(documentFileName); return "Success"; }catch (Exception ex){ return ex.ToString(); } }
public override void GeneratePreview(Stream docStream, IPreviewGenerationContext context) { var document = new Aspose.Words.Document(docStream); var pc = document.PageCount; // save the document only if this is the first round if (context.StartIndex == 0 || pc < 1) { context.SetPageCount(pc); } if (pc <= 0) { return; } int firstIndex; int lastIndex; var loggedPageError = false; context.SetIndexes(pc, out firstIndex, out lastIndex); for (var i = firstIndex; i <= lastIndex; i++) { try { using (var imgStream = new MemoryStream()) { var options = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Png) { PageIndex = i, Resolution = context.PreviewResolution }; document.Save(imgStream, options); if (imgStream.Length == 0) { continue; } context.SavePreviewAndThumbnail(imgStream, i + 1); } } catch (Exception ex) { if (Tools.HandlePageError(ex, i + 1, context, !loggedPageError)) { return; } loggedPageError = true; } } }
/// <summary> ///获取Doc页总数 /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static int getDocCount(string filePath) { var words = new Aspose.Words.Document(filePath); Aspose.Words.Saving.ImageSaveOptions imageSaveOptions = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Jpeg); imageSaveOptions.Resolution = 90; // 默认128 int pagecount = words.PageCount; return(pagecount); }
private Aspose.Words.Paragraph FindParagraph(Aspose.Words.Document document, string startsWith) { foreach (Aspose.Words.Section section in document.Sections) { var node = section.Body.Paragraphs.Where(x => x.ToString(Aspose.Words.SaveFormat.Text).Trim().StartsWith(startsWith)).LastOrDefault(); if (node != null) { return(node as Aspose.Words.Paragraph); } } return(default);
///<Summary> /// ConvertDocToEPUB method to convert doc file to EPUB format ///</Summary> public Response ConvertDocToEPUB(string fileName, string folderName, string userEmail) { return(ProcessTask(fileName, folderName, ".epub", false, false, delegate(string inFilePath, string outPath, string zipOutFolder) { // Load the document from disk. Aspose.Words.Document doc = new Aspose.Words.Document(inFilePath); // Save the document in EPUB format. doc.Save(outPath); })); }
public void CustomRemove() { //ExStart //ExFor:DocumentPropertyCollection.Remove //ExId:RemoveCustomProperties //ExSummary:Removes a custom document property. Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Properties.doc"); doc.CustomDocumentProperties.Remove("Authorized Date"); //ExEnd }
public void IsDictionaryRegisteredEx() { //ExStart //ExFor:Hyphenation.IsDictionaryRegistered(string) //ExSummary:Shows how to open check if some dictionary is registered. Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.doc"); Aspose.Words.Hyphenation.RegisterDictionary("en-US", MyDir + @"hyph_en_US.dic"); Console.WriteLine(Aspose.Words.Hyphenation.IsDictionaryRegistered("en-US")); // True //ExEnd }
public void PropertyTypes() { //ExStart //ExFor:DocumentProperty.Type //ExFor:DocumentProperty.ToBool //ExFor:DocumentProperty.ToInt //ExFor:DocumentProperty.ToDouble //ExFor:DocumentProperty.ToString //ExFor:DocumentProperty.ToDateTime //ExFor:PropertyType //ExSummary:Retrieves the types and values of the custom document properties. Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Properties.doc"); foreach (DocumentProperty prop in doc.CustomDocumentProperties) { Console.WriteLine(prop.Name); switch (prop.Type) { case PropertyType.String: Console.WriteLine("It's a string value."); Console.WriteLine(prop.ToString()); break; case PropertyType.Boolean: Console.WriteLine("It's a boolean value."); Console.WriteLine(prop.ToBool()); break; case PropertyType.Number: Console.WriteLine("It's an integer value."); Console.WriteLine(prop.ToInt()); break; case PropertyType.DateTime: Console.WriteLine("It's a date time value."); Console.WriteLine(prop.ToDateTime()); break; case PropertyType.Double: Console.WriteLine("It's a double value."); Console.WriteLine(prop.ToDouble()); break; case PropertyType.Other: Console.WriteLine("Other value."); break; default: throw new Exception("Unknown property type."); } } //ExEnd }
public void BuiltInNamedAccess() { //ExStart //ExFor:BuiltInDocumentProperties.Item(String) //ExFor:DocumentProperty.ToString //ExSummary:Retrieves a built-in document property by name. Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Properties.doc"); DocumentProperty prop = doc.BuiltInDocumentProperties["Keywords"]; Console.WriteLine(prop.ToString()); //ExEnd }
public string ConvertToHtml(string importFile) { string bodyHtml = string.Empty; if (!string.IsNullOrEmpty(importFile)) { try { //保存上传文件 UploadFile uf = new UploadFile(); uf.SetMaxSizeM(1000); //上传文件大小 string url = "/UpLoadFile/"; //文件保存路径 string saveFolder = Server.MapPath(url); uf.SetFileDirectory(saveFolder); string filesName = System.Web.HttpContext.Current.Request.Params["importFile"]; HttpPostedFile file = System.Web.HttpContext.Current.Request.Files[filesName]; var reponseMessage = uf.Save(file, "FileImport");//保存文件 string readPath = Server.MapPath("/UpLoadFile/FileImport/" + reponseMessage.FileName); string savePath = Server.MapPath("/UpLoadFile/FileImport/"); //读取word文件内容并保存至html文件中 string strSaveFileName = savePath + DateTime.Now.ToString("yyyyMMddHHmmss") + ".html"; Aspose.Words.Document awd = new Aspose.Words.Document(readPath); awd.Save(strSaveFileName, Aspose.Words.SaveFormat.Html); //读取html文件中body内容 using (StreamReader reader = new StreamReader(strSaveFileName, Encoding.UTF8)) { bodyHtml += reader.ReadToEnd(); } Regex reg = new Regex("(?is)<body[^>]*>(?<body>.*?)</body>"); bodyHtml = reg.Match(bodyHtml).Groups["body"].Value; bodyHtml = bodyHtml.Replace(" ", ""); Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase); //新建一个matches的MatchCollection对象 保存 匹配对象个数(img标签) MatchCollection matches = regImg.Matches(bodyHtml); //遍历所有的img标签对象 foreach (Match match in matches) { bodyHtml = bodyHtml.Replace(match.Groups["imgUrl"].Value, "/UpLoadFile/FileImport/" + match.Groups["imgUrl"].Value); } System.IO.File.Delete(readPath); System.IO.File.Delete(strSaveFileName); } catch (Exception ex) { Common.LogHelper.LogHelper.WriteLog("【知识库草稿列表上传附件】" + ex.ToString() + "/n" + ex.StackTrace); } } return(bodyHtml); }
private async static Task SaveImage(string word, string tempFile) { await Task.Run(() => { using (FileStream stream = new FileStream(word, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { Aspose.Words.Document doc = new Aspose.Words.Document(stream); doc.Save(tempFile, Aspose.Words.SaveFormat.Png); } return(tempFile); }); }
static void ConvertWordToPdf(string wordFilePath, string pdfFilePath) { try { new Aspose.Words.License().SetLicense(new MemoryStream(Convert.FromBase64String(Key))); Aspose.Words.Document document = new Aspose.Words.Document(wordFilePath); document.Save(pdfFilePath, Aspose.Words.SaveFormat.Pdf); } catch (FileNotFoundException) { } }
//Word報表 public static void WordReport_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { object[] result = (object[])e.Result; string reportName = (string)result[0]; string path = (string)result[1]; Aspose.Words.Document doc = (Aspose.Words.Document)result[2]; string path2 = (string)result[3]; bool PrintStudetnList = (bool)result[4]; Aspose.Cells.Workbook wb = (Aspose.Cells.Workbook)result[5]; string Message = "" + result[6]; if (File.Exists(path2)) { int i = 1; while (true) { string newPath = Path.GetDirectoryName(path2) + "\\" + Path.GetFileNameWithoutExtension(path2) + (i++) + Path.GetExtension(path2); if (!File.Exists(newPath)) { path2 = newPath; break; } } } if (PrintStudetnList) { MemoryStream memoryStream = new MemoryStream(); doc.Save(memoryStream, Aspose.Words.SaveFormat.Doc); ePaperCloud ePaperCloud = new ePaperCloud(); ePaperCloud.upload_ePaper(Convert.ToInt32(School.DefaultSchoolYear), Convert.ToInt32(School.DefaultSemester) , reportName, "", memoryStream, ePaperCloud.ViewerType.Student, ePaperCloud.FormatType.Docx, Message); wb.Save(path2); FISCA.Presentation.MotherForm.SetStatusBarMessage(reportName + "產生完成"); System.Diagnostics.Process.Start(path2); } else { int schoolYear = Convert.ToInt32(School.DefaultSchoolYear); int semester = Convert.ToInt32(School.DefaultSemester); MemoryStream memoryStream = new MemoryStream(); doc.Save(memoryStream, Aspose.Words.SaveFormat.Doc); ePaperCloud ePaperCloud = new ePaperCloud(); ePaperCloud.upload_ePaper(schoolYear, semester, reportName, "", memoryStream, ePaperCloud.ViewerType.Student, ePaperCloud.FormatType.Docx, Message); FISCA.Presentation.MotherForm.SetStatusBarMessage(reportName + "產生完成"); } }
public void ContainsEx() { //ExStart //ExFor:VariableCollection.Contains //ExSummary:Shows how to check if a collection of document variables contains a key. Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.doc"); doc.Variables.Add("doc", "Word processing document"); Console.WriteLine(doc.Variables.Contains("doc")); // True Console.WriteLine(doc.Variables.Contains("Word processing document")); // False //ExEnd }
public void UnregisterDictionaryEx() { //ExStart //ExFor:Hyphenation.UnregisterDictionary(string) //ExSummary:Shows how to un-register a dictionary Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.doc"); Aspose.Words.Hyphenation.RegisterDictionary("en-US", MyDir + @"hyph_en_US.dic"); Aspose.Words.Hyphenation.UnregisterDictionary("en-US"); Console.WriteLine(Aspose.Words.Hyphenation.IsDictionaryRegistered("en-US")); // False //ExEnd }
public static void createFileDownload(string reportTemplate, DataSet reportData, string saveName, Aspose.Words.SaveFormat saveFormat, Aspose.Words.SaveType saveType, HttpResponse Response) { Aspose.Words.License license = new Aspose.Words.License(); license.SetLicense("Aspose.Words.lic"); //Open the template document Aspose.Words.Document reportDoc = new Aspose.Words.Document(reportTemplate); // Fill the fields in the document with user data. reportDoc.MailMerge.ExecuteWithRegions(reportData); // Send the document in Word format to the client browser with an option to save to disk or open inside the current browser. reportDoc.Save(saveName, saveFormat, saveType, Response); }
public void GetPositionByIndexEx() { //ExStart //ExFor:TabStopCollection.GetPositionByIndex //ExSummary:Shows how to find a tab by it's index and get its position. Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.doc"); Aspose.Words.Paragraph paragraph = (Aspose.Words.Paragraph)doc.GetChild(Aspose.Words.NodeType.Paragraph, 0, true); paragraph.ParagraphFormat.TabStops.Add(85, Aspose.Words.TabAlignment.Left, Aspose.Words.TabLeader.Dashes); paragraph.ParagraphFormat.TabStops.Add(170, Aspose.Words.TabAlignment.Left, Aspose.Words.TabLeader.Dashes); Console.WriteLine(paragraph.ParagraphFormat.TabStops.GetPositionByIndex(1)); // 170 //ExEnd }
public void UseCustomToolTips() { Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.doc"); //ExStart //ExFor:SwfSaveOptions //ExFor:SwfSaveOptions.ToolTipsFontName //ExFor:SwfSaveOptions.ToolTips //ExFor:SwfViewerControlIdentifier //ExSummary:Shows how to change the the tooltips used in the embedded document viewer. // We create an instance of SwfSaveOptions to specify our custom tooltips. SwfSaveOptions options = new SwfSaveOptions(); // By default, all tooltips are in English. You can specify font used for each tooltip. // Note that font specified should contain proper glyphs normally used in tooltips. options.ToolTipsFontName = "Times New Roman"; // The following code will set the tooltip used for each control. In our case we will change the tooltips from English // to Russian. options.ToolTips[SwfViewerControlIdentifier.TopPaneActualSizeButton] = "Оригинальный размер"; options.ToolTips[SwfViewerControlIdentifier.TopPaneFitToHeightButton] = "По высоте страницы"; options.ToolTips[SwfViewerControlIdentifier.TopPaneFitToWidthButton] = "По ширине страницы"; options.ToolTips[SwfViewerControlIdentifier.TopPaneZoomOutButton] = "Увеличить"; options.ToolTips[SwfViewerControlIdentifier.TopPaneZoomInButton] = "Уменшить"; options.ToolTips[SwfViewerControlIdentifier.TopPaneSelectionModeButton] = "Режим выделения текста"; options.ToolTips[SwfViewerControlIdentifier.TopPaneDragModeButton] = "Режим перетаскивания"; options.ToolTips[SwfViewerControlIdentifier.TopPaneSinglePageScrollLayoutButton] = "Одностнаничный скролинг"; options.ToolTips[SwfViewerControlIdentifier.TopPaneSinglePageLayoutButton] = "Одностраничный режим"; options.ToolTips[SwfViewerControlIdentifier.TopPaneTwoPageScrollLayoutButton] = "Двустраничный скролинг"; options.ToolTips[SwfViewerControlIdentifier.TopPaneTwoPageLayoutButton] = "Двустраничный режим"; options.ToolTips[SwfViewerControlIdentifier.TopPaneFullScreenModeButton] = "Полноэкранный режим"; options.ToolTips[SwfViewerControlIdentifier.TopPanePreviousPageButton] = "Предыдущая старница"; options.ToolTips[SwfViewerControlIdentifier.TopPanePageField] = "Введите номер страницы"; options.ToolTips[SwfViewerControlIdentifier.TopPaneNextPageButton] = "Следующая страница"; options.ToolTips[SwfViewerControlIdentifier.TopPaneSearchField] = "Введите искомый текст"; options.ToolTips[SwfViewerControlIdentifier.TopPaneSearchButton] = "Искать"; // Left panel. options.ToolTips[SwfViewerControlIdentifier.LeftPaneDocumentMapButton] = "Карта документа"; options.ToolTips[SwfViewerControlIdentifier.LeftPanePagePreviewPaneButton] = "Предварительный просмотр страниц"; options.ToolTips[SwfViewerControlIdentifier.LeftPaneAboutButton] = "О приложении"; options.ToolTips[SwfViewerControlIdentifier.LeftPaneCollapsePanelButton] = "Свернуть панель"; // Bottom panel. options.ToolTips[SwfViewerControlIdentifier.BottomPaneShowHideBottomPaneButton] = "Показать/Скрыть панель"; //ExEnd doc.Save(MyDir + "SwfSaveOptions.ToolTips Out.swf", options); }
public void ClearAllAttrsEx() { //ExStart //ExFor:TabStopCollection.Clear //ExSummary:Shows how to clear a document of all tab stops. Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.TableOfContents.doc"); foreach (Aspose.Words.Paragraph para in doc.GetChildNodes(Aspose.Words.NodeType.Paragraph, true)) { para.ParagraphFormat.TabStops.Clear(); } doc.Save(ExDir + "Document.AllTabStopsRemoved Out.doc"); //ExEnd }
public void GetIndexByPositionEx() { //ExStart //ExFor:TabStopCollection.GetIndexByPosition //ExSummary:Shows how to look up a position to see if a tab stop exists there, and if so, obtain its index. Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.doc"); Aspose.Words.Paragraph paragraph = (Aspose.Words.Paragraph)doc.GetChild(Aspose.Words.NodeType.Paragraph, 0, true); paragraph.ParagraphFormat.TabStops.Add(Aspose.Words.ConvertUtil.MillimeterToPoint(30), Aspose.Words.TabAlignment.Left, Aspose.Words.TabLeader.Dashes); // An output of -1 signifies that there is no tab stop at that position. Console.WriteLine(paragraph.ParagraphFormat.TabStops.GetIndexByPosition(Aspose.Words.ConvertUtil.MillimeterToPoint(30))); // 0 Console.WriteLine(paragraph.ParagraphFormat.TabStops.GetIndexByPosition(Aspose.Words.ConvertUtil.MillimeterToPoint(60))); // -1 //ExEnd }
public void AddEx() { //ExStart //ExFor:VariableCollection.Add //ExSummary:Shows how to create document variables and add them to a document's variable collection. Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.doc"); doc.Variables.Add("doc", "Word processing document"); doc.Variables.Add("docx", "Word processing document"); doc.Variables.Add("txt", "Word processing document"); // Duplicate values can be stored but adding a duplicate name overwrites the old one. doc.Variables.Add("txt", "Plain text file"); doc.Variables.Add("bmp", "Image"); doc.Variables.Add("png", "Image"); //ExEnd }
public void RegisterDictionaryEx() { //ExStart //ExFor:Hyphenation.RegisterDictionary(String, Stream) //ExFor:Hyphenation.RegisterDictionary(String, String) //ExSummary:Shows how to open and register a dictionary from a file. Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.doc"); // Register by string Aspose.Words.Hyphenation.RegisterDictionary("en-US", MyDir + @"hyph_en_US.dic"); // Register by stream Stream dictionaryStream = new FileStream(MyDir + @"hyph_de_CH.dic", FileMode.Open); Aspose.Words.Hyphenation.RegisterDictionary("de-CH", dictionaryStream); //ExEnd }
public void ClearEx() { //ExStart //ExFor:VariableCollection.Clear //ExSummary:Shows how to clear all document variables from a document. Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.doc"); doc.Variables.Add("doc", "Word processing document"); doc.Variables.Add("docx", "Word processing document"); doc.Variables.Add("txt", "Plain text file"); doc.Variables.Add("bmp", "Image"); doc.Variables.Add("png", "Image"); doc.Variables.Clear(); Console.WriteLine(doc.Variables.Count); // 0 //ExEnd }
protected void btnIssueFreeFormatMessage_Click(object sender, EventArgs e) { Aspose.Words.License license = new Aspose.Words.License(); license.SetLicense("Aspose.Words.lic"); //Open template string path = Context.Server.MapPath("~/DesktopModules/TrainingCoreBanking/BankProject/Report/Template/IssueFreeFormatMessage.doc"); //Open the template document Aspose.Words.Document doc = new Aspose.Words.Document(path); //Execute the mail merge. DataSet ds = new DataSet(); ds = SQLData.B_BFREETEXTMESSAGE_Report(hiddenId.Value); // Fill the fields in the document with user data. doc.MailMerge.ExecuteWithRegions(ds); //moas mat thoi jan voi cuc gach nay woa // Send the document in Word format to the client browser with an option to save to disk or open inside the current browser. doc.Save("IssueFreeFormatMessage_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf", Aspose.Words.SaveFormat.Pdf, Aspose.Words.SaveType.OpenInApplication, Response); }
public void AddEx() { //ExStart //ExFor:TabStopCollection.Add(TabStop) //ExFor:TabStopCollection.Add(Double, TabAlignment, TabLeader) //ExSummary:Shows how to create and add tabStop objects to a document. Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.doc"); Aspose.Words.Paragraph paragraph = (Aspose.Words.Paragraph)doc.GetChild(Aspose.Words.NodeType.Paragraph, 0, true); // Create a TabStop object and add it into the document Aspose.Words.TabStop tabStop = new Aspose.Words.TabStop(84.99, Aspose.Words.TabAlignment.Left, Aspose.Words.TabLeader.Dashes); paragraph.ParagraphFormat.TabStops.Add(tabStop); // Add a TabStop without explicitly initializing paragraph.ParagraphFormat.TabStops.Add(169.98, Aspose.Words.TabAlignment.Left, Aspose.Words.TabLeader.Dashes); doc.Save(ExDir + "Document.AddedTabStops Out.doc"); //ExEnd }
//ExStart //ExFor:IMailMergeDataSource //ExFor:IMailMergeDataSource.TableName //ExFor:IMailMergeDataSource.MoveNext //ExFor:IMailMergeDataSource.GetValue //ExFor:IMailMergeDataSource.GetChildDataSource //ExFor:MailMerge.Execute(IMailMergeDataSource) //ExSummary:Performs mail merge from a custom data source. public void MailMergeCustomDataSource() { // Create some data that we will use in the mail merge. CustomerList customers = new CustomerList(); customers.Add(new Customer("Thomas Hardy", "120 Hanover Sq., London")); customers.Add(new Customer("Paolo Accorti", "Via Monte Bianco 34, Torino")); // Open the template document. Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "MailMerge.CustomDataSource.doc"); // To be able to mail merge from your own data source, it must be wrapped // into an object that implements the IMailMergeDataSource interface. CustomerMailMergeDataSource customersDataSource = new CustomerMailMergeDataSource(customers); // Now you can pass your data source into Aspose.Words. doc.MailMerge.Execute(customersDataSource); doc.Save(MyDir + "MailMerge.CustomDataSource Out.doc"); }
public void GetEnumeratorEx() { //ExStart //ExFor:VariableCollection.GetEnumerator //ExSummary:Shows how to obtain an enumerator from a collection of document variables and use it. Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.doc"); doc.Variables.Add("doc", "Word processing document"); doc.Variables.Add("docx", "Word processing document"); doc.Variables.Add("txt", "Plain text file"); doc.Variables.Add("bmp", "Image"); doc.Variables.Add("png", "Image"); var enumerator = doc.Variables.GetEnumerator(); while (enumerator.MoveNext()) { DictionaryEntry de = (DictionaryEntry)enumerator.Current; Console.WriteLine("Name: {0}, Value: {1}", de.Key, de.Value); } //ExEnd }
public void HideControls() { //ExStart //ExFor:SwfSaveOptions.TopPaneControlFlags //ExFor:SwfTopPaneControlFlags //ExFor:SwfSaveOptions.ShowSearch //ExSummary:Shows how to choose which controls to display in the embedded document viewer. Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.doc"); // Create an instance of SwfSaveOptions and set some buttons as hidden. SwfSaveOptions options = new SwfSaveOptions(); // Hide all the buttons with the exception of the page control buttons. Similar flags can be used for the left control pane as well. options.TopPaneControlFlags = SwfTopPaneControlFlags.HideAll | SwfTopPaneControlFlags.ShowActualSize | SwfTopPaneControlFlags.ShowFitToWidth | SwfTopPaneControlFlags.ShowFitToHeight | SwfTopPaneControlFlags.ShowZoomIn | SwfTopPaneControlFlags.ShowZoomOut; // You can also choose to show or hide the main elements of the viewer. Hide the search control. options.ShowSearch = false; //ExEnd doc.Save(MyDir + "SwfSaveOptions.HideControls Out.swf", options); }
public void SignEx() { //ExStart //ExFor:Sign(String, String, CertificateHolder, String, DateTime) //ExFor:Sign(Stream, Stream, CertificateHolder, String, DateTime) //ExId:SignEx //ExSummary:Shows how to use RemoveAllSignatures. Aspose.Words.CertificateHolder ch = Aspose.Words.CertificateHolder.Create(ExDir + "MyPkcs12.pfx", "My password"); //By String Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.doc"); string outputDocFileName = ExDir + "Document.Signed.doc"; Aspose.Words.DigitalSignatureUtil.Sign(doc.OriginalFileName, outputDocFileName, ch, "My comment", DateTime.Now); //By Stream System.IO.Stream docInStream = new System.IO.FileStream(ExDir + "Document.doc", System.IO.FileMode.Open); System.IO.Stream docOutStream = new System.IO.FileStream(ExDir + "Document.Signed.doc", System.IO.FileMode.OpenOrCreate); Aspose.Words.DigitalSignatureUtil.Sign(docInStream, docOutStream, ch, "My comment", DateTime.Now); //ExEnd }
public void RemoveAllSignaturesEx() { //ExStart //ExFor:DigitalSignatureUtil.RemoveAllSignatures(stream, stream) //ExFor:DigitalSignatureUtil.RemoveAllSignatures(string, string) //ExSummary:Shows how to use RemoveAllSignatures. Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.doc"); //By stream: System.IO.Stream docStreamIn = new System.IO.FileStream(ExDir + "Document.doc", System.IO.FileMode.Open); System.IO.Stream docStreamOut = new System.IO.FileStream(ExDir + "Document.NoSignatures.FromStream.doc", System.IO.FileMode.Create); Aspose.Words.DigitalSignatureUtil.RemoveAllSignatures(docStreamIn, docStreamOut); docStreamIn.Close(); docStreamOut.Close(); //By string: string outFileName = ExDir + "Document.NoSignatures.FromString.doc"; Aspose.Words.DigitalSignatureUtil.RemoveAllSignatures(doc.OriginalFileName, outFileName); //ExEnd }
public static void Run() { // ExStart:ManipulateObjects // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OLEObjects(); // Load a Visio diagram Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx"); // Get page of the Visio diagram by name Aspose.Diagram.Page page = diagram.Pages.GetPage("Page-1"); // Get shape of the Visio diagram by ID Aspose.Diagram.Shape OLE_Shape = page.Shapes.GetShape(2); // Filter shapes by type Foreign if (OLE_Shape.Type == Aspose.Diagram.TypeValue.Foreign) { if (OLE_Shape.ForeignData.ForeignType == ForeignType.Object) { Stream Ole_stream = new MemoryStream(OLE_Shape.ForeignData.ObjectData); // Get format of the OLE file object Aspose.Words.FileFormatInfo info = Aspose.Words.FileFormatUtil.DetectFileFormat(Ole_stream); if (info.LoadFormat == Aspose.Words.LoadFormat.Doc || info.LoadFormat == Aspose.Words.LoadFormat.Docx) { // Modify an OLE object var doc = new Aspose.Words.Document(new MemoryStream(OLE_Shape.ForeignData.ObjectData)); doc.Range.Replace("testing", "Aspose", false, true); MemoryStream outStream = new MemoryStream(); doc.Save(outStream, Aspose.Words.SaveFormat.Docx); // Save back an OLE object OLE_Shape.ForeignData.ObjectData = outStream.ToArray(); } } } // Save Visio diagram diagram.Save(dataDir + "ManipulateObjects_out.vsdx", SaveFileFormat.VSDX); // ExEnd:ManipulateObjects }
public void MailMergeCustomDataSource() { // Create some data that we will use in the mail merge. CustomerList customers = new CustomerList(); customers.Add(new Customer("Thomas Hardy", "120 Hanover Sq., London")); customers.Add(new Customer("Paolo Accorti", "Via Monte Bianco 34, Torino")); // Create some data for nesting in the mail merge. customers[0].Orders.Add(new Order("Rugby World Cup Cap", 2)); customers[0].Orders.Add(new Order("Rugby World Cup Ball", 1)); customers[1].Orders.Add(new Order("Rugby World Cup Guide", 1)); // Open the template document. Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "NestedMailMerge.CustomDataSource.doc"); // To be able to mail merge from your own data source, it must be wrapped // into an object that implements the IMailMergeDataSource interface. CustomerMailMergeDataSource customersDataSource = new CustomerMailMergeDataSource(customers); // Now you can pass your data source into Aspose.Words. doc.MailMerge.ExecuteWithRegions(customersDataSource); doc.Save(ExDir + "NestedMailMerge.CustomDataSource Out.doc"); }
/// <summary> /// 开始处理文件 /// </summary> private DataGridViewRow DoIt(DataGridViewRow dr) { DateTime dtStart = DateTime.Now; StringBuilder strRemark = new StringBuilder(); dr.Cells["是否已处理"].Value = "是"; try { #region 验证扩展名及是否为文本文件 string currentExt = dr.Cells["扩展名"].Value.ToString(); string[] defaultExt = { "xls", "xlsx","csv" , "doc", "docx"/*, "ppt", "pptx","pdf"*/ };//这些格式由aspose去处理 string[] excelExt = { "xls", "xlsx", "csv" }; string[] docExt = { "doc", "docx" }; //string[] pptExt = { "ppt", "pptx" }; //string[] pdfExt = { "pdf"}; bool isDefaultExt = defaultExt.Contains(currentExt); bool isExcelExt = excelExt.Contains(currentExt); bool isDocExt = docExt.Contains(currentExt); //bool isPPTExt = pptExt.Contains(currentExt); //bool isPdfExt = pdfExt.Contains(currentExt); bool isTxtFile = XCLNetTools.FileHandler.ComFile.IsTextFile(dr.Cells["路径"].Value.ToString()); if (!isDefaultExt && !isTxtFile && this.ckIsContent.Checked) { //非aspose能处理的文件,且非文本文件,则不能替换内容,只能替换文件名! dr.Cells["备注"].Value = "不支持替换该文件的内容!"; dr.Cells["是否处理成功"].Value = "否"; dr.DefaultCellStyle.ForeColor = System.Drawing.Color.Red; return dr; } #endregion Regex reg = null; #region 是否启用正则替换 if (this.ckIsRegexp.Checked) { reg = this.ckIsNotIgnoreLowerCase.Checked?new Regex(this.txtOldValue.Text):new Regex(this.txtOldValue.Text, RegexOptions.IgnoreCase); } else { string newExpStr = this.ckIsWhole.Checked ? string.Format(@"\b{0}\b",Regex.Escape(this.txtOldValue.Text)) :Regex.Escape(this.txtOldValue.Text); reg = this.ckIsNotIgnoreLowerCase.Checked ? new Regex(newExpStr) : new Regex(newExpStr, RegexOptions.IgnoreCase); } #endregion #region 复制到输出目录并判断是否替换文件名 string filePath = dr.Cells["路径"].Value.ToString(); filePath = filePath.Replace(this.openFileFolderPath.TrimEnd('\\'), this.txtOutPutPath.Text.TrimEnd('\\')); string filetitle = XCLNetTools.FileHandler.ComFile.GetFileName(filePath, false); #region 是否替换文件名 if (this.ckIsFileName.Checked) { strRemark.AppendFormat("文件名替换【{0}】处;", reg.Matches(filetitle).Count); filetitle = reg.Replace(filetitle, this.txtNew.Text); } #endregion filetitle = string.Format("{0}{1}{2}", this.txtFileFirstName.Text, filetitle, this.txtFileLastName.Text); filePath = XCLNetTools.FileHandler.ComFile.GetFileFolderPath(filePath) + "\\" + filetitle + "." + XCLNetTools.FileHandler.ComFile.GetExtName(filePath); XCLNetTools.FileHandler.ComFile.CopyFile(dr.Cells["路径"].Value.ToString(), filePath); if (!System.IO.File.Exists(filePath)) { dr.Cells["备注"].Value = "输出目录中的文件未找到!"; dr.Cells["是否处理成功"].Value = "否"; dr.DefaultCellStyle.ForeColor = System.Drawing.Color.Red; return dr; } #endregion #region 开始替换文件内容 if (this.ckIsContent.Checked) { int replaceCount = 0; if (isDefaultExt) { if (isExcelExt) { #region 处理excel文件 Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook(filePath); for (int i = 0; i < wb.Worksheets.Count; i++) { Aspose.Cells.Cells sheetCells = wb.Worksheets[i].Cells; for (int cellsRowIndex = 0; cellsRowIndex < sheetCells.MaxDataRow+1; cellsRowIndex++) { for (int cellsColumn = 0; cellsColumn < sheetCells.MaxDataColumn+1; cellsColumn++) { Aspose.Cells.Cell currentCell = sheetCells[cellsRowIndex, cellsColumn]; string cellValue = Convert.ToString(currentCell.Value); if (!string.IsNullOrEmpty(cellValue)) { replaceCount += reg.Matches(cellValue).Count; cellValue = reg.Replace(cellValue, this.txtNew.Text); currentCell.PutValue(cellValue); } } } } if (replaceCount > 0) { wb.Save(filePath); } #endregion } else if (isDocExt) { #region 处理word //正则无法使用特殊正则,如\s带\的。 Aspose.Words.Document wordDocument = new Aspose.Words.Document(filePath); replaceCount= wordDocument.Range.Replace(reg, this.txtNew.Text); wordDocument.Save(filePath); #endregion } //else if (isPPTExt) //{ // #region 处理PPT // Aspose.Slides.Pptx.PresentationEx pptPres = new Aspose.Slides.Pptx.PresentationEx(filePath); // #endregion //} //else if (isPdfExt) //{ // #region 处理pdf文件 // Aspose.Pdf.Kit.PdfContentEditor pdfEditor = new Aspose.Pdf.Kit.PdfContentEditor(); // pdfEditor.BindPdf(filePath); // pdfEditor.ReplaceText(this.txtOldValue.Text, this.txtNew.Text); // pdfEditor.Save(filePath); // #endregion //} } else { #region 处理文本文件 string fileContent = System.IO.File.ReadAllText(filePath, System.Text.Encoding.Default); replaceCount = reg.Matches(fileContent).Count; fileContent = reg.Replace(fileContent, this.txtNew.Text); System.IO.File.WriteAllText(filePath, fileContent, System.Text.Encoding.Default); #endregion } strRemark.AppendFormat("文件内容替换【{0}】处;", replaceCount); } #endregion if (strRemark.Length > 0) { dr.Cells["备注"].Value = strRemark.ToString(); } dr.Cells["是否处理成功"].Value = "是"; dr.DefaultCellStyle.ForeColor = System.Drawing.Color.Green; } catch(Exception e) { dr.Cells["是否处理成功"].Value = "否"; dr.DefaultCellStyle.ForeColor = System.Drawing.Color.Red; dr.Cells["备注"].Value = e.Message; } DateTime dtEnd = DateTime.Now; dr.Cells["处理用时"].Value =Math.Round((decimal)(dtEnd.Subtract(dtStart).TotalMilliseconds/1000.0),1); return dr; }