private void FormEmail_Load(object sender, EventArgs e) { txtHost.Text = settings.Host; txtForm.Text = settings.From; txtName.Text = settings.Name; txtPassword.Text = settings.Password; txtSubjec.Text = settings.EmailSubject; txtPort.Text = settings.Port; if (settings.Encryption == "SSL") { comboBox1.SelectedIndex = 1; } else if (settings.Encryption == "") { comboBox1.SelectedIndex = 0; } DirectoryInfo d = new DirectoryInfo(textBox2.Text + "\\"); //Assuming Test is your Folder FileInfo[] Files = d.GetFiles(".\\" + "email*.dotx"); //Getting Text files if (Files.Length == 0) { //Create word document Document document = new Document(); Paragraph p = document.AddSection().AddParagraph(); TextRange txtRang = p.AppendText("H63TWX11072"); txtRang.CharacterFormat.FontName = "C39HrP60DlTt"; txtRang.CharacterFormat.FontSize = 80; txtRang.CharacterFormat.TextColor = Color.SeaGreen; Section section = document.AddSection(); //Initialize a Header Instance HeaderFooter header = document.Sections[0].HeadersFooters.Header; //Add Header Paragraph and Format Paragraph paragraph = header.AddParagraph(); paragraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left; //Append Picture for Header Paragraph and Format Spire.Doc.Fields.DocPicture headerimage = paragraph.AppendPicture(Image.FromFile(@"dackeasy_logo.png")); headerimage.VerticalAlignment = ShapeVerticalAlignment.Bottom; paragraph = section.AddParagraph(); string str = "Dear <CONTACT PERSON>," + "\r\n"; paragraph.AppendText(str); str = "As an independent Word .NET component, Spire.Doc for .NET doesn't need Microsoft Word to be installed on the machine. However, it can incorporate Microsoft Word document creation capabilities into any developers.NET applications.As an independent Word .NET component, Spire.Doc for .NET doesn't need Microsoft Word to be installed on the machine. However, it can incorporate Microsoft Word document creation capabilities into any developers’.NET applications." + "\r\n"; paragraph.AppendText(str); document.SaveToFile("email.dotx", FileFormat.Dotx); d = new DirectoryInfo(Directory.GetCurrentDirectory());//Assuming Test is your Folder Files = d.GetFiles("email*.dotx"); } comboBox2.DataSource = Files; comboBox2.DisplayMember = "demo"; //Center(this); }
// Cохранение файла DOC private void LoadDoc_Click(object sender, RoutedEventArgs e) { Spire.Doc.Document document = new Spire.Doc.Document(); document.LoadFromFile(pathDOC); document.SaveToFile("ScheduleByCorrespondence.HTML", Spire.Doc.FileFormat.Html); FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://212.86.101.101/ScheduleByCorrespondence.html"); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential("anonymous", ""); byte[] fileContents; using (StreamReader sourceStream = new StreamReader(pathDOC)) { fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); } request.ContentLength = fileContents.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(fileContents, 0, fileContents.Length); } using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { Message.Content = ($"Upload File Complete, status {response.StatusDescription}"); } }
private void PdfExtractWordAndPicture(string savePathCache, string midName)//参数:保存地址,处理过程中文件名称(不包含后缀) { #region 提取PDF中的文字 try { PdfDocument doc = new PdfDocument(); doc.LoadFromFile(savePathCache + "\\" + midName + ".pdf"); //加载文件 StringBuilder content = new StringBuilder(); foreach (PdfPageBase page in doc.Pages) { content.Append(page.ExtractText()); } System.IO.File.WriteAllText(savePathCache + "\\mid.txt", content.ToString()); Spire.Doc.Document document = new Spire.Doc.Document(); document.LoadFromFile(savePathCache + "\\mid.txt"); document.Replace(" ", "", true, true); document.Replace("Evaluation Warning : The document was created with Spire.PDF for .NET.", "", true, true); document.SaveToFile(savePathCache + "\\" + midName + ".doc", Spire.Doc.FileFormat.Doc); File.Delete(savePathCache + "\\mid.txt"); } catch (Exception) { MessageBox.Show("请填写正确的路径"); } #endregion #region 提取PDF中的图片 //创建一个PdfDocument类对象并加载PDF sample Spire.Pdf.PdfDocument mydoc = new Spire.Pdf.PdfDocument(); mydoc.LoadFromFile(savePathCache + "\\" + midName + ".pdf"); //声明一个IList类,元素为image IList <Image> images = new List <Image>(); //遍历PDF文档中诊断是否包含图片,并提取图片 foreach (PdfPageBase page in mydoc.Pages) { if (page.ExtractImages() != null) { foreach (Image image in page.ExtractImages()) { images.Add(image); } } } mydoc.Close(); //遍历提取的图片,保存并命名图片 int index = 0; foreach (Image image in images) { String imageFileName = String.Format(midName + "Image-{0}.png", index++); image.Save(savePathCache + "\\" + imageFileName, ImageFormat.Png); } #endregion }
public void AddWeizhu(string filename, string str) { Dictionary <string, object> dic = new Dictionary <string, object> { { "内容", this.Hulue(str.Trim()) } }; var list = _sqlhelper.GetAnySet(Setting._cijuchachongbiao, dic); string text = list[0]["来源"].ToString(); Spire.Doc.Document document = new Spire.Doc.Document(); document.LoadFromFile(filename); TextSelection[] selectionArray = document.FindAllString(str, false, true); if (selectionArray != null) { TextSelection[] selectionArray2 = selectionArray; int index = 0; while (true) { if (index >= selectionArray2.Length) { document.SaveToFile(filename); document.Dispose(); this.ClearShuiyin(filename); break; } TextSelection selection = selectionArray2[index]; Spire.Doc.Fields.Footnote entity = selection.GetAsOneRange().OwnerParagraph.AppendFootnote(Spire.Doc.FootnoteType.Endnote); entity.TextBody.AddParagraph().AppendText(text); Paragraph ownerParagraph = selection.GetAsOneRange().OwnerParagraph; ownerParagraph.ChildObjects.Insert(ownerParagraph.ChildObjects.IndexOf(selection.GetAsOneRange()) + 1, entity); index++; } } }
private void BtnDoc_Click(object sender, RoutedEventArgs e) { SaveFileDialog fileDialog = new SaveFileDialog(); Person person = new Person(); string path = person.FilePath; fileDialog.Filter = "Text documents (.doc)|*.doc"; fileDialog.Title = "Save an Doc File"; if (fileDialog.ShowDialog() == true) { string fileName = fileDialog.FileName; string extesion = System.IO.Path.GetExtension(fileName); switch (extesion) { case ".doc": //do something here Spire.Doc.Document document = new Spire.Doc.Document(); document.LoadText(path); document.SaveToFile(fileName, FileFormat.Doc); document.Close(); MessageBox.Show("Conversion Successful...."); break; } } /* * document.SaveToFile(System.IO.Path.Combine(path, "TestWordDoc.docx"), FileFormat.Doc); * document.LoadFromFile(System.IO.Path.Combine(path, "TestTxt.txt")); * * document.LoadFromFile(System.IO.Path.Combine(docPath, "TestWordDoc.docx")); * string readText = File.ReadAllText(System.IO.Path.Combine(docPath, "TestTxt.txt")); */ }
/// <summary> /// 将word保存为doc格式 /// </summary> /// <param name="o"></param> public void SaveDoc(object o) { string file = o as string; //保存文档为doc格式 string parent = Directory.GetParent(MySetting.Default.fieldirectory).FullName; string savedir = file.Replace(parent, ""); if (!Directory.Exists(savedir)) { Directory.CreateDirectory(savedir); } string filename = Path.GetFileNameWithoutExtension(file); string savepath = savedir + "\\" + filename + ".docx"; Spire.Doc.Document mydoc = new Spire.Doc.Document(); mydoc.SaveToFile(savepath, FileFormat.Docx); mydoc.Close(); //去水印 Aspose.Words.Document aspdoc = new Aspose.Words.Document(savepath); aspdoc.Sections[0].Body.Paragraphs.RemoveAt(0); aspdoc.Save(savedir + "\\" + filename + ".doc", Aspose.Words.SaveFormat.Doc); //删除docx文件 File.Delete(savepath); }
private void BtnPdf_Click(object sender, RoutedEventArgs e) { SaveFileDialog fileDialog = new SaveFileDialog(); Person person = new Person(); string path = person.FilePath; string imgPath = person.ImagePath; fileDialog.Filter = "Text documents (.pdf)|*.pdf"; fileDialog.Title = "Save an Pdf File"; if (fileDialog.ShowDialog() == true) { string fileName = fileDialog.FileName; string extesion = System.IO.Path.GetExtension(fileName); switch (extesion) { case ".pdf": Spire.Doc.Document document = new Spire.Doc.Document(); document.LoadText(path); document.SaveToFile(fileName, FileFormat.PDF); document.Close(); MessageBox.Show("Conversion Successful...."); break; } } // this.Close(); }
/// <summary> /// Получить временный поток сконвертированного документа. /// </summary> /// <param name="document_bytes">Входящие байты текущего документа</param> /// <param name="tempFilePath">Путь сохранения файла</param> /// <returns>Временный поток нового файла (В случае ошибки вернёт null)</returns> public static MemoryStream getConvertFileDoc(byte[] document_bytes, string tempFilePath) { using (MemoryStream fileStream = new MemoryStream(document_bytes)) { HLogger.log.Debug("Чтение MemoryStream"); SPD.Document document = new SPD.Document(fileStream); HLogger.log.Debug("Инициализация документа:"); if (!File.Exists(tempFilePath)) { document.SaveToFile(tempFilePath, SPD.FileFormat.PDF); HLogger.log.Debug("Сохранение временного файла"); } else { HLogger.log.Debug("Подобный временный файл уже существует"); } try { MemoryStream result = new MemoryStream(File.ReadAllBytes(tempFilePath)); return(result); } catch { HLogger.log.Error("Ошибка при создании временного потока"); return(null); } } }
/// <summary> /// 添加尾注 /// </summary> /// <param name="filename"></param> /// <param name="str"></param> public void AddWeizhu(string filename, string str) { //获得数据库中str对应的来源 string str_sql = $"select 来源 from {Setting._cijuchachongbiao} where 内容='{Hulue(str.Trim())}'"; Dictionary <string, object> dic = mysqliter.ExecuteRow(str_sql, null, null)[0] as Dictionary <string, object>; string laiyuan = dic["来源"].ToString(); Spire.Doc.Document mydoc = new Spire.Doc.Document(); mydoc.LoadFromFile(filename); TextSelection[] texts = mydoc.FindAllString(str, false, true); if (texts == null) { return; } //给所有查找到的文字添加脚注 foreach (TextSelection item in texts) { //实例化一个脚注的同时,直接创建在指定textselection所在的段落 Spire.Doc.Fields.Footnote footnote = item.GetAsOneRange().OwnerParagraph.AppendFootnote(Spire.Doc.FootnoteType.Endnote); //向脚注内添加文字 footnote.TextBody.AddParagraph().AppendText(laiyuan); //获得这个自然段 Spire.Doc.Documents.Paragraph mypara = item.GetAsOneRange().OwnerParagraph; //向这个段落内的子节点添加脚注 mypara.ChildObjects.Insert(mypara.ChildObjects.IndexOf(item.GetAsOneRange()) + 1, footnote); } mydoc.SaveToFile(filename); mydoc.Dispose(); //去水印 ClearShuiyin(filename); }
private void button1_Click(object sender, EventArgs e) { #region 将pdf分成许多份小文档 Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument(); pdf.LoadFromFile(textBox1.Text); label4.Text = "转换中......"; label4.Refresh(); for (int i = 0; i < pdf.Pages.Count; i += 5) { int j = 0; Spire.Pdf.PdfDocument newpdf = new Spire.Pdf.PdfDocument(); for (j = i; j >= i && j <= i + 4; j++) { if (j < pdf.Pages.Count) { Spire.Pdf.PdfPageBase page; page = newpdf.Pages.Add(pdf.Pages[j].Size, new Spire.Pdf.Graphics.PdfMargins(0)); pdf.Pages[j].CreateTemplate().Draw(page, new PointF(0, 0)); } } newpdf.SaveToFile(textBox2.Text + "\\" + j.ToString() + ".pdf"); PdfExtractWordAndPicture(textBox2.Text, j.ToString()); } #endregion #region 合并word文档 string filePath0 = textBox2.Text + "\\" + '5' + ".doc"; for (int i = 10; i <= 0 - pdf.Pages.Count % 5 + pdf.Pages.Count; i += 5) { string filePath2 = textBox2.Text + "\\" + i.ToString() + ".doc"; Spire.Doc.Document doc = new Spire.Doc.Document(filePath0); doc.InsertTextFromFile(filePath2, Spire.Doc.FileFormat.Doc); doc.SaveToFile(filePath0, Spire.Doc.FileFormat.Doc); } Spire.Doc.Document mydoc1 = new Spire.Doc.Document(); mydoc1.LoadFromFile(textBox2.Text + "\\" + '5' + ".doc"); mydoc1.SaveToFile(textBox2.Text + "\\" + "TheLastTransform" + ".doc", Spire.Doc.FileFormat.Doc); for (int i = 5; i <= 5 - pdf.Pages.Count % 5 + pdf.Pages.Count; i += 5) { File.Delete(textBox2.Text + "\\" + i.ToString() + ".doc"); File.Delete(textBox2.Text + "\\" + i.ToString() + ".pdf"); } #endregion label4.Text = "转换完成"; label4.Refresh(); }
private void button3_Click(object sender, EventArgs e) { Spire.Doc.Document docSpire = new Spire.Doc.Document(@"C:\TEMP\Teste6.docx"); //Spire.Doc.Document docSpire = new Spire.Doc.Document(); Spire.Doc.Section secao = docSpire.Sections[0]; Spire.Doc.HeaderFooter cabecalho = secao.HeadersFooters.Header; Spire.Doc.Documents.Paragraph para1 = cabecalho.AddParagraph(); para1.AppendRTF(richTextBox1.Rtf); //Spire.Doc.Section secao2 = docSpire.AddSection(); Spire.Doc.Documents.Paragraph para2 = secao.AddParagraph(); para2.AppendRTF(richTextBox2.Rtf); docSpire.SaveToFile(@"C:\TEMP\Teste6.docx"); }
public void CleanFile() { //Instantiate a Document object Spire.Doc.Document document = new Spire.Doc.Document(); //Load the Word document document.LoadFromFile(@"C:\Users\Konstantin\Desktop\WSIiZ\QRCodeSample\QRCodeSample\QR.docx"); //Remove paragraphs from every section in the document foreach (Spire.Doc.Section section in document.Sections) { section.Paragraphs.Clear(); } //Save the document document.SaveToFile(@"C:\Users\Konstantin\Desktop\WSIiZ\QRCodeSample\QRCodeSample\QR.docx", FileFormat.Docx2013); }
//Copies mail merge template into .docx and adds page break public void AddTemplate() { Spire.Doc.Document sourceDoc = new Spire.Doc.Document(@"C:\Users\Konstantin\Desktop\WSIiZ\QRCodeSample\QR.docx"); Spire.Doc.Document destinationDoc = new Spire.Doc.Document(@"C:\Users\Konstantin\Desktop\WSIiZ\QRCodeSample\QRCodeSample\QR.docx"); foreach (Spire.Doc.Section sec in sourceDoc.Sections) { foreach (DocumentObject obj in sec.Body.ChildObjects) { destinationDoc.Sections[0].Body.ChildObjects.Add(obj.Clone()); Spire.Doc.Documents.Paragraph newParagraph = new Spire.Doc.Documents.Paragraph(destinationDoc); newParagraph.AppendBreak(BreakType.PageBreak); destinationDoc.LastSection.Paragraphs.Add(newParagraph); } } destinationDoc.SaveToFile(@"C:\Users\Konstantin\Desktop\WSIiZ\QRCodeSample\QRCodeSample\QR.docx", FileFormat.Docx2013); }
static void Main(string[] args) { using (var stream = new MemoryStream()) { // Generate RTF (using MigraDoc) var migraDoc = new MigraDoc.DocumentObjectModel.Document(); var section = migraDoc.AddSection(); var paragraph = section.AddParagraph(); paragraph.AddFormattedText("Hello World!", TextFormat.Bold); var rtfDocumentRenderer = new RtfDocumentRenderer(); rtfDocumentRenderer.Render(migraDoc, stream, false, null); // Convert RTF to DOCX (using Spire.Doc) var spireDoc = new Spire.Doc.Document(); spireDoc.LoadFromStream(stream, FileFormat.Auto); spireDoc.SaveToFile("D:\\example.docx", FileFormat.Docx); } }
static void Ziple() { string inputPath = "C:/Users/Administrator/Desktop/metinDeneme.docx"; Spire.Doc.Document document = new Spire.Doc.Document(); document.LoadFromFile(inputPath); //Convert Word to PDF document.SaveToFile("metin.PDF", FileFormat.PDF); byte[] array = File.ReadAllBytes("metin.PDF"); webReferans.WebService1 ws = new webReferans.WebService1(); byte[] zipByteArray = ws.ZipThat("metin.pdf", array); File.WriteAllBytes("C:/Users/Administrator/Desktop/test.zip", zipByteArray); Console.WriteLine("İşlem Başarılı ."); Console.ReadLine(); }
private void Finalizer(Content content) { using (var outputDocument = new TemplateProcessor(_outputPath) .SetRemoveContentControls(true)) { outputDocument.FillContent(content); outputDocument.SaveChanges(); } Document document = new Document(); document.LoadFromFile(_outputPath); //Convert Word to PDF document.SaveToFile("toPDF.PDF", FileFormat.PDF); //Launch Document Process.Start("toPDF.PDF"); }
static void MultiZiple() { string inputPath1 = "C:/Users/Administrator/Desktop/metinDeneme.docx"; string inputPath2 = "C:/Users/Administrator/Desktop/metinDeneme2.docx"; Spire.Doc.Document doc1 = new Spire.Doc.Document(); Spire.Doc.Document doc2 = new Spire.Doc.Document(); doc1.LoadFromFile(inputPath1); doc2.LoadFromFile(inputPath2); doc1.SaveToFile("metin1.PDF", FileFormat.PDF); doc2.SaveToFile("metin2.PDF", FileFormat.PDF); byte[] metin1_Array = File.ReadAllBytes("metin1.PDF"); byte[] metin2_Array = File.ReadAllBytes("metin2.PDF"); webReferans.WebService1 ws = new webReferans.WebService1(); byte[] multiZipArray = ws.ZipMulti("metin1.PDF", "metin2.PDF", metin1_Array, metin2_Array); File.WriteAllBytes("C:/Users/Administrator/Desktop/testMultiZip.zip", multiZipArray); }
static void Main(string[] args) { int opcaoDeslogado = 0; int opcaoLogado = 0; int opcaoTransacao = 0; int opcaoExtrato = 0; TransacaoRepositorio transacaoRepositorio = new TransacaoRepositorio(); UsuarioRepositorio usuarioRepositorio = new UsuarioRepositorio(); do { MenuUtils.MenuDeslogado(); opcaoDeslogado = int.Parse(Console.ReadLine()); switch (opcaoDeslogado) { case 1: UsuarioViewController.CadastrarUsuario(); break; case 2: UsuarioViewModel usuarioRecuperado = UsuarioViewController.EfetuarLogin(); if (usuarioRecuperado != null) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"Seja bem vindo - {usuarioRecuperado.Nome}"); Console.ResetColor(); do { MenuUtils.MenuLogado(); opcaoLogado = int.Parse(Console.ReadLine()); switch (opcaoLogado) { case 1: do { MenuUtils.MenuTransacao(); opcaoTransacao = int.Parse(Console.ReadLine()); switch (opcaoTransacao) { case 1: TransacaoViewController.CadastrarDespesa(); break; case 2: TransacaoViewController.DepositarNaConta(); break; } } while (opcaoTransacao != 0); break; case 2: do { MenuUtils.MenuExtrato(); opcaoExtrato = int.Parse(Console.ReadLine()); switch (opcaoExtrato) { case 1: TransacaoViewController.ListarCredito(); break; case 2: TransacaoViewController.ListarDeposito(); break; case 3: TransacaoViewController.SaldoAtual(); break; case 4: TransacaoViewController.Zipar(); break; case 5: List <TransacaoViewModel> extratoDeTransacoes = transacaoRepositorio.Listar(); List <TransacaoViewModel> extratoDeDepositos = transacaoRepositorio.ListarDeposito(); Spire.Doc.Document document = new Spire.Doc.Document(); Paragraph paragraph = document.AddSection().AddParagraph(); foreach (var item in extratoDeTransacoes) { Console.ForegroundColor = ConsoleColor.DarkBlue; paragraph.AppendText($"Descrição: {item.Descricao} \n Valor do Crédito: {item.ValorCredito} \n Data da Transação: {item.DataDaTransacao}\n"); Console.ResetColor(); } foreach (var item in extratoDeDepositos) { Console.ForegroundColor = ConsoleColor.DarkBlue; paragraph.AppendText($"Descrição: {item.Descricao} \n Valor do Deposito: {item.ValorDeposito} \n Data da Transação: {item.DataDaTransacao}\n"); Console.ResetColor(); } document.SaveToFile("Sample.doc", FileFormat.Doc); try { System.Diagnostics.Process.Start("Sample.doc"); } catch { } break; } } while (opcaoExtrato != 0); break; } } while (opcaoLogado != 0); } break; case 3: UsuarioViewController.ListarUsuario(); List <UsuarioViewModel> listaDeUsuarios = usuarioRepositorio.Listar(); Spire.Doc.Document documento = new Spire.Doc.Document(); Paragraph paragrafo = documento.AddSection().AddParagraph(); foreach (var item in listaDeUsuarios) { paragrafo.AppendText($"Nome: {item.Nome}\nData de Nascimento: {item.DataNascimento}\nEmail: {item.Email}\nSenha: {item.Senha}\n\n"); documento.SaveToFile("Sample.doc", FileFormat.Doc); try { System.Diagnostics.Process.Start("Sample.doc"); } catch { } } break; default: break; } } while (opcaoDeslogado != 0); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("Obrigado pela atenção!"); Console.ResetColor(); }
private void button1_Click(object sender, EventArgs e) { Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("pl-PL"); using (DocX document = DocX.Load(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój1.docx")) { // Check if all the replace patterns are used in the loaded document. document.ReplaceText("@PrzykładowyTekstDoZmiany0", "PierwszaWstawkaBezSPacji_Znakmi!#$%^)&()", false, System.Text.RegularExpressions.RegexOptions.None, new Formatting() { Bold = true }); document.ReplaceText("@PrzykładowyTekstDoZmiany1", "Zwykły tekst ", false, System.Text.RegularExpressions.RegexOptions.None, new Formatting() { Bold = true }); document.ReplaceText("@PrzykładowyTekstDoZmiany2", "Zwykły tekst, dodany przez aplikację ( ) ", false, System.Text.RegularExpressions.RegexOptions.None, new Formatting() { Bold = true }); var p = document.InsertParagraph(); p.Append("Przykładowy czerwony tekst dodany na końcu,") .Font(new Font("Arial")) .FontSize(25) .Color(System.Drawing.Color.Red) .Bold() .Append(" zawierający dodatkowe inne niebieskie formatowanie").Font(new Font("Times New Roman")).Color(System.Drawing.Color.Blue).Italic() .SpacingAfter(40); // Save this document to disk. document.SaveAs(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.docx"); using (DocX document1 = DocX.Load(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój1.docx")) { using (DocX document3 = DocX.Load(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.docx")) { document1.InsertDocument(document3, true); document1.SaveAs(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój3.docx"); } } var n = DateTime.Now; var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second)); tempDi.Create(); /* * This example loads each document into a byte array, then into a memory stream, so that the document can be opened for writing without * modifying the source document. */ //foreach (var file in Directory.GetFiles("../../", "*.docx")) //{ // ConvertToHtml(file, tempDi.FullName); //} byte[] byteArray = File.ReadAllBytes(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.docx"); using (MemoryStream memoryStream = new MemoryStream()) { memoryStream.Write(byteArray, 0, byteArray.Length); using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true)) { HtmlConverterSettings settings = new HtmlConverterSettings() { PageTitle = "My Page Title" }; XElement html = HtmlConverter.ConvertToHtml(doc, settings); File.WriteAllText(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.html", html.ToStringNewLineOnAttributes()); } } string test = File.ReadAllText(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.hmtl"); //Byte[] res = null; //using (MemoryStream ms = new MemoryStream()) //{ // var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(test, PdfSharp.PageSize.A4); // pdf.Save(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.pdf"); // res = ms.ToArray(); //} //Load Document Spire.Doc.Document document2 = new Spire.Doc.Document(); document2.LoadFromFile(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.docx"); //Convert Word to PDF document2.SaveToFile("toPDF.PDF", FileFormat.PDF); //Launch Document System.Diagnostics.Process.Start("toPDF.PDF"); string[] pdfFiles = { @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF", @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF", @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF", @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF", @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF", @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF" }; PdfDocument outputPDFDocument = new PdfDocument(); foreach (string pdfFile in pdfFiles) { PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import); outputPDFDocument.Version = inputPDFDocument.Version; foreach (PdfPage page in inputPDFDocument.Pages) { outputPDFDocument.AddPage(page); } } outputPDFDocument.Save(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF2.PDF"); } }
private void button1_Click(object sender, EventArgs e) { string filename = Application.StartupPath + "\\bin\\" + Global.templateName + ".doc"; Spire.Doc.Document document = new Spire.Doc.Document(filename, FileFormat.Docx); Spire.Doc.Fields.TextBox textBox = document.TextBoxes[12]; Spire.Doc.Documents.Paragraph paragraph = textBox.Body.AddParagraph(); Spire.Doc.Fields.TextRange textRange = paragraph.AppendText(textBox1.Text); document.SaveToFile(filename, FileFormat.Docx); object filename1 = Environment.CurrentDirectory.ToString() + "\\bin\\" + Global.templateName + ".doc"; string ImagePath = pictureBox1.ImageLocation; string strKey = "7.6.2 开门测试期间温度变化曲线图"; object MissingValue = Type.Missing; bool isFindSealLoc = false; Microsoft.Office.Interop.Word.Application wp = null; Microsoft.Office.Interop.Word.Document wd = null; try { wp = new Microsoft.Office.Interop.Word.Application(); wd = wp.Documents.Open(ref filename1, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue); wp.Selection.Find.ClearFormatting(); wp.Selection.Find.Replacement.ClearFormatting(); wp.Selection.Find.Text = strKey; object objReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone; if (wp.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref objReplace, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue)) { object Anchor = wp.Selection.Range; object LinkToFile = false; object SaveWithDocument = true; Microsoft.Office.Interop.Word.InlineShape Inlineshape = wp.Selection.InlineShapes.AddPicture( ImagePath, ref LinkToFile, ref SaveWithDocument, ref Anchor); Inlineshape.Select(); Microsoft.Office.Interop.Word.Shape shape = Inlineshape.ConvertToShape(); shape.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind; isFindSealLoc = true; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { if (wd != null) { wd.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wd); wd = null; } if (wp != null) { wp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wp); wp = null; } MessageBox.Show("导入成功!"); } this.Close(); }
public ActionResult Download(RegisterExternalLoginModel mReg, string Command, int id = 0) { if (Command == "MS Word") { try { var userGuid = new Guid(User.Identity.GetUserId()); //WebSecurity.GetUserId(User.Identity.Name); var userId = BitConverter.ToInt32(userGuid.ToByteArray(), 0); var responses = _db.Responses.Where(x => x.UserId == userId).OrderBy(x => x.Ordinal).ThenBy(x => x.SubOrdinal).ThenBy(x => x.QQOrd).ToList(); var categories = new List <string> { "Personal Information", "Employment", "Education", "Coursework", "Certifications", "Licenses", "Credentials", "Training" }; var fui = new FormatUserInformation(responses, categories); var formatted = fui.Format(); var ms = MakeWordFile.CreateDocument(formatted); var ms2 = new MemoryStream(ms.ToArray()); Spire.Doc.Document doc = new Spire.Doc.Document(ms2); doc.SaveToFile("Portfolio.docx", Spire.Doc.FileFormat.Docx, System.Web.HttpContext.Current.Response, HttpContentType.Attachment); //Response.Clear(); //Response.AddHeader("content-disposition", "attachment; filename=\"Portfolio.docx\""); //Response.ContentType = "application/msword"; //ms2.WriteTo(Response.OutputStream); //Response.End(); } catch (Exception ex) { Response.Write(ex.Message); } } else if (Command == "Pdf") { try { var userGuid = new Guid(User.Identity.GetUserId()); //WebSecurity.GetUserId(User.Identity.Name); var userId = BitConverter.ToInt32(userGuid.ToByteArray(), 0); var responses = _db.Responses.Where(x => x.UserId == userId).OrderBy(x => x.Ordinal).ThenBy(x => x.SubOrdinal).ThenBy(x => x.QQOrd).ToList(); var categories = new List <string> { "Personal Information", "Employment", "Education", "Coursework", "Certifications", "Licenses", "Credentials", "Training" }; var fui = new FormatUserInformation(responses, categories); var formatted = fui.Format(); var ms = MakeWordFile.CreateDocument(formatted); var ms2 = new MemoryStream(ms.ToArray()); Spire.Doc.Document doc = new Spire.Doc.Document(ms2); doc.SaveToFile("Portfolio.pdf", Spire.Doc.FileFormat.PDF, System.Web.HttpContext.Current.Response, HttpContentType.Attachment); } catch (Exception ex) { Response.Write(ex.Message); } } else if (Command == "Certificate") { var userGuid = new Guid(User.Identity.GetUserId()); var userIdStr = User.Identity.GetUserId(); var userId = BitConverter.ToInt32(userGuid.ToByteArray(), 0); var user = _udb.Users.FirstOrDefault(s => s.Id == userIdStr); UserLevel userLevel = _db.UserLevels.Where(q => q.UserId == userId).First(); var certificateDate = ((DateTime)userLevel.FinalStepLevelDate).ToString("d"); var certificateLevel = userLevel.FinalStepLevel; var signature = "Zelda Boyd"; string firstName = ""; string lastName = ""; string middleInitial = ""; if (user != null) { if (user.FirstName != null && user.FirstName != "") { firstName = user.FirstName; } else { firstName = "FirstName"; } if (user.LastName != null && user.LastName != "") { lastName = user.LastName; } else { lastName = "LastName"; } if (user.MiddleInitial != null && user.MiddleInitial != "") { middleInitial = user.MiddleInitial; } else { middleInitial = ""; } } firstName = user.FirstName; middleInitial = user.MiddleInitial; lastName = user.LastName; string fullName = firstName + " " + (middleInitial != "" ? middleInitial + " " : "") + lastName; var appRoot = Request.PhysicalApplicationPath; var file = appRoot + "Content\\VPDR_Certificate_10.docx"; var newFile = appRoot + "Content\\VPDR_Certificate_" + lastName + "_" + firstName + ".docx"; var newPdf = appRoot + "Content\\VPDR_Certificate_" + lastName + "_" + firstName + ".pdf"; Spire.Doc.Document doc = new Spire.Doc.Document(); doc.LoadFromFile(file); doc.Replace("PROVIDER", fullName, true, true); doc.Replace("LEVEL", certificateLevel, true, true); doc.Replace("DATE", certificateDate, true, true); doc.Replace("SIGNATURE", signature, true, true); //doc.SaveToFile(newPdf, Spire.Doc.FileFormat.PDF); //doc.SaveToFile(newFile, Spire.Doc.FileFormat.Docx); var newPdfName = "VPDR_Certificate_" + lastName + "_" + firstName + ".pdf"; doc.SaveToFile(newPdfName, Spire.Doc.FileFormat.PDF, System.Web.HttpContext.Current.Response, HttpContentType.Attachment); } if (ModelState.IsValid) { return(RedirectToAction("Index")); } return(RedirectToAction("Download")); }
public IActionResult Batchs(string command, string ids) { var response = ResponseModelFactory.CreateInstance; string sWebRootFolder = _hostingEnvironment.WebRootPath + "\\UploadFiles\\ImportUserInfoWord\\"; var timeInfo = DateTime.Now.ToString("yyyyMMddHHmmss"); var wordName = timeInfo + "address.docx"; string wordUrl = sWebRootFolder + wordName; MemoryStream ms = new MemoryStream(); XWPFDocument m_Docx = new XWPFDocument(); m_Docx.Write(ms); ms.Flush(); SaveToFile(ms, wordUrl); List <string> list = new List <string>(); using (_dbContext) { //document111.LoadFromFile(sWebRootFolder + "test.docx"); Document document111 = new Document(); document111.LoadFromFile(wordUrl); Section section = document111.Sections[0]; document111.Watermark = null; section.Paragraphs[0].AppendBookmarkStart("picture"); section.Paragraphs[0].AppendBookmarkEnd("picture"); var parameters = ids.Split(",").Select((id, index) => new SqlParameter(string.Format("@p{0}", index), id)).ToList(); var parameterNames = string.Join(", ", parameters.Select(p => p.ParameterName)); var entities = _dbContext.GrabageRoom.Where(x => ids.IndexOf(x.GarbageRoomUuid.ToString()) >= 0).ToList(); for (int i = 0; i < entities.Count; i++) { var pata = _hostingEnvironment.WebRootPath + EWM.GetEWM2("d_" + entities[i].GarbageRoomUuid.ToString(), _hostingEnvironment, entities[i].Ljname); //实例化BookmarksNavigator类,指定需要添加图片的书签“” BookmarksNavigator bn = new BookmarksNavigator(document111); bn.MoveToBookmark("picture", true, true); //添加段落,加载图片并插入到段落 Section section0 = document111.AddSection(); Spire.Doc.Documents.Paragraph paragraph = section0.AddParagraph(); Image image = Image.FromFile(pata); //DocPicture picture = paragraph.AppendPicture(image); DocPicture picture = document111.Sections[0].Paragraphs[0].AppendPicture(image); picture.Width = 160; picture.Height = 180; //picture.HorizontalPosition = 100.0f; //picture.VerticalPosition = 100.0f; bn.InsertParagraph(paragraph); document111.Sections.Remove(section0); //string output = sWebRootFolder + "test.docx"; document111.SaveToFile(wordUrl, FileFormat.Docx); } list.Add(wordUrl); //关闭进程 document111.Dispose(); var time = DateTime.Now.ToString("yyyyMMddHHmmssfff"); var check = ZIP.CompressMulti(list, _hostingEnvironment.WebRootPath + "\\UploadFiles\\EWM\\" + time, false); if (check) { response.SetSuccess("导出成功"); response.SetData("\\UploadFiles\\EWM\\" + time + ".zip"); } else { response.SetFailed("导出失败"); } return(Ok(response)); } }
private void button1_Click(object sender, EventArgs e) { object filename1 = Application.StartupPath + "\\bin\\" + Global.templateName; object G_Missing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document wordDoc; wordDoc = wordApp.Documents.Open(filename1); wordDoc.ActiveWindow.Visible = false;//打开word Microsoft.Office.Interop.Word.Range myRange = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f = myRange.Find; f.Text = "布点数量:"; f.ClearFormatting(); bool finded = f.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange = wordDoc.Range(myRange.End, myRange.End + 10); myRange.Text = textBox1.Text; Microsoft.Office.Interop.Word.Range myRange1 = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f1 = myRange1.Find; f1.Text = "仪表编号:"; f1.ClearFormatting(); bool finded1 = f1.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange1 = wordDoc.Range(myRange1.End, myRange1.End + 13); myRange1.Text = textBox1.Text; Microsoft.Office.Interop.Word.Range myRange2 = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f2 = myRange2.Find; f2.Text = "检测状态:空载(半载或满载)"; f2.ClearFormatting(); bool finded2 = f2.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange2 = wordDoc.Range(myRange2.End - 9, myRange2.End); myRange2.Text = comboBox1.Text; wordDoc.Save(); wordDoc.Close(ref G_Missing, ref G_Missing, ref G_Missing); wordApp.Quit(ref G_Missing, ref G_Missing, ref G_Missing); wordApp = null; string ImagePath = pictureBox1.ImageLocation; string strKey = "示意图:(上层,中层,下层)"; object MissingValue = Type.Missing; bool isFindSealLoc = false; Microsoft.Office.Interop.Word.Application wp = null; Microsoft.Office.Interop.Word.Document wd = null; try { wp = new Microsoft.Office.Interop.Word.Application(); wd = wp.Documents.Open(ref filename1, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue); wp.Selection.Find.ClearFormatting(); wp.Selection.Find.Replacement.ClearFormatting(); wp.Selection.Find.Text = strKey; object objReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone; if (wp.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref objReplace, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue)) { object Anchor = wp.Selection.Range; object LinkToFile = false; object SaveWithDocument = true; Microsoft.Office.Interop.Word.InlineShape Inlineshape = wp.Selection.InlineShapes.AddPicture( ImagePath, ref LinkToFile, ref SaveWithDocument, ref Anchor); Inlineshape.Select(); Microsoft.Office.Interop.Word.Shape shape = Inlineshape.ConvertToShape(); shape.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind; isFindSealLoc = true; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { if (wd != null) { wd.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wd); wd = null; } if (wp != null) { wp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wp); wp = null; } } string filename = Environment.CurrentDirectory.ToString() + "\\bin\\" + Global.templateName + ".doc"; Spire.Doc.Document document = new Spire.Doc.Document(filename, FileFormat.Docx); Spire.Doc.Fields.TextBox textBox = document.TextBoxes[0]; Spire.Doc.Documents.Paragraph paragraph = textBox.Body.AddParagraph(); Spire.Doc.Fields.TextRange textRange = paragraph.AppendText(textBox3.Text); document.SaveToFile(filename, FileFormat.Docx); this.Close(); }
private void CreateDocument(object o) { ExcelInfo ei = o as ExcelInfo; dgv_task.Rows[ei._id - 1].Cells[4].Value = "正在准备"; //获得 table DataTable dt_split = ei._data; //读取excel,得到行数 /*生成一个新的word*/ Spire.Doc.Document spdoc = new Spire.Doc.Document(); /*循环把list中的mycu内容添加到word文档*/ for (int rowindex = 0; rowindex < dt_split.Rows.Count; rowindex++) { dgv_task.Rows[ei._id - 1].Cells[4].Value = (100 * Convert.ToDecimal(rowindex + 1) / Convert.ToDecimal(dt_split.Rows.Count)).ToString("00.00") + "%"; //更新状态栏文字 //string str_statue = "正在生成第{0}个,共{1}个……"; //UpdateStatue(string.Format(str_statue, rowindex - 1, lastrow - 1)); ///载入一个空白文档 spdoc.LoadFromFile(Environment.CurrentDirectory + @"\newdoc.docx"); for (int i = Global.list_myuc.Count - 1; i >= 0; i--) { //设置文本 string str_n = string.Empty; //设置空行 for (int ji = 0; ji < Global.list_myuc[i].mysetter.konghang; ji++) { str_n += "\n"; } //添加一个段落 Spire.Doc.Documents.Paragraph parainsert = spdoc.LastSection.AddParagraph(); //Spire.Doc.Documents.Paragraph parainsert = spdoc.CreateParagraph(); TextRange tx = parainsert.AppendText(GetContent(Global.list_myuc[i].mysetter.listcolumn, rowindex, dt_split) + str_n); //字体名称 tx.CharacterFormat.FontName = Global.list_myuc[i].mysetter.fontname; //字体大小 tx.CharacterFormat.FontSize = Global.list_myuc[i].mysetter.fontsize; //设置行距 switch (Global.list_myuc[i].mysetter.hangjustyle) { case "单倍行距": parainsert.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.AtLeast; break; case "1.5倍行距": parainsert.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.Exactly; break; case "2倍行距": parainsert.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.Multiple; break; default: parainsert.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.Exactly; parainsert.Format.LineSpacing = Global.list_myuc[i].mysetter.hangjuvalue; break; } //首行缩进 parainsert.Format.SetFirstLineIndent(Global.list_myuc[i].mysetter.suojin); //首行缩进 //粗体 tx.CharacterFormat.Bold = Global.list_myuc[i].mysetter.bold == 1 ? true : false; switch (Global.list_myuc[i].mysetter.juzhong) { case "左对齐": parainsert.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left; break; case "居中": parainsert.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; break; case "右对齐": parainsert.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right; break; } } SectionCollection sections = spdoc.Sections; //创建一个HeaderFooter类实例,添加页脚 for (int i = 0; i < sections.Count; i++) { sections[i].PageSetup.Margins.Top = 72f; sections[i].PageSetup.Margins.Left = 90f; sections[i].PageSetup.Margins.Bottom = 72f; sections[i].PageSetup.Margins.Right = 90f; Spire.Doc.HeaderFooter footer = sections[i].HeadersFooters.Footer; Spire.Doc.Documents.Paragraph footerPara = footer.AddParagraph(); //添加字段类型为页码,添加当前页、分隔线以及总页数 footerPara.AppendField("页码", FieldType.FieldPage); footerPara.AppendText(" / "); footerPara.AppendField("总页数", FieldType.FieldNumPages); footerPara.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; } /*保存文档*/ //组成文件名 List <string> strfilename = new List <string>(); for (int i = 0; i < Global.listfilename.Count; i++) { string filename_element = Regex.Replace(dt_split.Rows[rowindex][Global.listfilename[i] + 1].ToString(), @"[\s/\:*?''<>|]", ""); strfilename.Add(filename_element); } spdoc.BuiltinDocumentProperties.Author = "潜挖智库"; spdoc.SaveToFile(tbcunfang.Text + @"\" + string.Join("-", strfilename) + @".docx"); spdoc.Close(); } }
/// <summary> /// 將 Word 串流轉換為 PDF 串流(使用 Aspose.Words 套件) /// </summary> /// <param name="WordFileStreaming">Word 串流內容</param> /// <returns>PDF串流</returns> public static byte[] ConvertToPdf_AsposeWords(byte[] WordFileStreaming) { bool result = true; string msg = ""; MemoryStream ms = new MemoryStream(); FileStream fs = null; //利用 Spire.Doc 將 Word 串流資訊轉換為實體暫存檔案 Spire.Doc.Document spiredoc = new Spire.Doc.Document(); Stream tmpdoc = new MemoryStream(WordFileStreaming); spiredoc.LoadFromStream(tmpdoc, FileFormat.Docx); string tmpDocDir = HttpContext.Current.Server.MapPath("~/TmpDocs"); string tmpDocPath = Path.Combine(tmpDocDir, DateTime.Now.ToString("yyyyMMddHHmmss") + ".docx"); if (!Directory.Exists(tmpDocDir)) { Directory.CreateDirectory(tmpDocDir); } spiredoc.SaveToFile(tmpDocPath, FileFormat.Docx); //轉換成 PDF string tmpPdfFilePath = Path.Combine(tmpDocDir, DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf"); if (File.Exists(tmpDocPath)) { try { //轉換過程 Aspose.Words.Document srcDoc = new Aspose.Words.Document(tmpDocPath); // Save the document in PDF format. srcDoc.Save(tmpPdfFilePath, SaveFormat.Pdf); //將轉換後的 PDF 實體檔案串流化 fs = new FileStream(tmpPdfFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); //將 FileStream 轉存給 MemoryStream fs.CopyTo(ms); } catch (Exception ex) { result = false; msg = ex.Message; } finally { fs.Dispose(); //刪除產生的暫存 PDF 檔 File.Delete(tmpPdfFilePath); } //刪除產生的暫存 Word 檔 File.Delete(tmpDocPath); } // 回傳串流資訊 if (result) { return(ms.ToArray()); } else { return(null); } }
/****** 程式處理邏輯 ***** * * 1. 取得 docx 串流資訊,將其轉換為實體暫存檔案 * 2. 透過 Microsoft.Office.Interop.Word 套件將方才產生的 docx 暫存檔轉換為 PDF 實體檔案 * 3. 將 PDF 實體檔案轉換成串流資訊 * 4. 回傳前,將產生的暫存檔案 (docx, pdf) 移除 * 5. 回傳 PDF 串流資訊,完成 * ************************/ /// <summary> /// 將 Word 串流轉換為 PDF 串流 (使用 Microsoft.Office.Interop.Word 套件) /// </summary> /// <param name="WordFileStreaming">Word 串流內容</param> /// <returns>PDF串流</returns> public static byte[] ConvertToPdf_MicrosoftOfficeInteropWord(byte[] WordFileStreaming) { bool result = true; string msg = ""; MemoryStream ms = new MemoryStream(); FileStream fs = null; //利用 Spire.Doc 將 Word 串流資訊轉換為實體暫存檔案 Spire.Doc.Document spiredoc = new Spire.Doc.Document(); Stream tmpdoc = new MemoryStream(WordFileStreaming); spiredoc.LoadFromStream(tmpdoc, FileFormat.Docx); string tmpDocDir = HttpContext.Current.Server.MapPath("~/TmpDocs"); string tmpDocPath = Path.Combine(tmpDocDir, DateTime.Now.ToString("yyyyMMddHHmmss") + ".docx"); if (!Directory.Exists(tmpDocDir)) { Directory.CreateDirectory(tmpDocDir); } spiredoc.SaveToFile(tmpDocPath, FileFormat.Docx); //轉換成 PDF string tmpPdfFilePath = Path.Combine(tmpDocDir, DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf"); if (File.Exists(tmpDocPath)) { var appWord = new Application(); if (appWord.Documents != null) { var wordDocument = appWord.Documents.Open(tmpDocPath); if (wordDocument != null) { try { //將 Word 檔轉存成 PDF 實體檔案 wordDocument.ExportAsFixedFormat(tmpPdfFilePath, WdExportFormat.wdExportFormatPDF); //將轉換後的 PDF 實體檔案串流化 fs = new FileStream(tmpPdfFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); wordDocument.Close(); //將 FileStream 轉存給 MemoryStream fs.CopyTo(ms); } catch (Exception ex) { result = false; msg = ex.Message; } finally { fs.Dispose(); //刪除產生的暫存 PDF 檔 File.Delete(tmpPdfFilePath); } } } appWord.Quit(); //刪除產生的暫存 Word 檔 File.Delete(tmpDocPath); } if (result) { return(ms.ToArray()); } else { return(null); } }
public void Export(DataGridView dataGrid, string filename) { Spire.Doc.Document document = new Spire.Doc.Document(); Spire.Doc.Section section = document.AddSection(); section.PageSetup.Orientation = Spire.Doc.Documents.PageOrientation.Landscape; AddHeaderTitle(section); Spire.Doc.Table table = section.AddTable(true); String[] header = { "ID", "Full Name", "Date of birth", "Gender", "Phone", "Email", "Position" }; int RowCount = dataGrid.Rows.Count; int ColumnCount = dataGrid.Columns.Count; String[][] data = new String[RowCount][]; for (int i = 0; i < RowCount; i++) { data[i] = new String[ColumnCount]; } //add rows for (int c = 0; c < ColumnCount; c++) { for (int r = 0; r < RowCount; r++) { if (dataGrid.Rows[r].Cells[c].Value.GetType() == typeof(DateTime)) { data[r][c] = ((DateTime)dataGrid.Rows[r].Cells[c].Value).ToString("dd/MM/yyyy"); } else { data[r][c] = dataGrid.Rows[r].Cells[c].Value.ToString(); } } } table.ResetCells(data.Length + 1, header.Length); TableRow FRow = table.Rows[0]; FRow.IsHeader = false; FRow.Height = 23; //FRow.RowFormat.BackColor = Color.AliceBlue; for (int i = 0; i < header.Length; i++) { //Cell Alignment Spire.Doc.Documents.Paragraph p = FRow.Cells[i].AddParagraph(); FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle; p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; //Data Format Spire.Doc.Fields.TextRange TR = p.AppendText(header[i]); TR.CharacterFormat.FontName = "Calibri"; TR.CharacterFormat.FontSize = 14; TR.CharacterFormat.TextColor = Color.Black; TR.CharacterFormat.Bold = true; } //Data Row for (int r = 0; r < data.Length; r++) { TableRow DataRow = table.Rows[r + 1]; //Row Height DataRow.Height = 20; //C Represents Column. for (int c = 0; c < data[r].Length; c++) { //Cell Alignment DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle; //Fill Data in Rows Spire.Doc.Documents.Paragraph p2 = DataRow.Cells[c].AddParagraph(); Spire.Doc.Fields.TextRange TR2 = p2.AppendText(data[r][c]); //Format Cells p2.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; TR2.CharacterFormat.FontName = "Calibri"; TR2.CharacterFormat.FontSize = 12; TR2.CharacterFormat.TextColor = Color.Black; } } //Save and Launch document.SaveToFile(filename); MessageBox.Show("Document Created Successfully!", "Export File", MessageBoxButtons.OK, MessageBoxIcon.Information); document.Close(); }
static void Main(string[] args) { // Changes \ to / in the path string string oldstr = @"\"; string newstr = @"/"; string pdf_path_original = string.Empty; // Tells the file path Console.WriteLine("FILE PATH: "); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("ファイル パス: "); pdf_path_original = Console.ReadLine(); string pdf_path = pdf_path_original.Replace(oldstr, newstr); // Tells the file name Console.WriteLine(".pdf`s Name: "); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("ファイルの名前は: "); string pdf_file_name = Console.ReadLine(); string path_n_name = pdf_path + "/" + pdf_file_name + ".pdf"; // Tells the file alignment Console.WriteLine("Text alignment: "); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("テキスト配置: "); Console.WriteLine("1: Left (左), and Right (右), or 2: Middle (真ん中)"); string caseSwitch = Console.ReadLine(); Console.WriteLine(); // Tells the file start page and end page Console.WriteLine(".pdf`s Initial Page "); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("最初のページは: "); string startpage_string = Console.ReadLine(); int startpage = Int32.Parse(startpage_string); Console.WriteLine(".pdf`s Last Page "); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("最後のページは: "); string endpage_string = Console.ReadLine(); int endpage = Int32.Parse(endpage_string); // Creates blank pdf files for (int i = startpage; i <= endpage; i++) { string convi = i.ToString(); // Creates a temp folder for the pdf files System.IO.Directory.CreateDirectory(pdf_path + "/" + "temp"); System.IO.FileStream pdf_creator = new System.IO.FileStream(pdf_path + "/" + "temp" + "/" + convi + ".pdf", System.IO.FileMode.Create); pdf_creator.Close(); } // Tells the attributes from the new pdf files, and the original pdf source iTextSharp.text.pdf.PdfReader reader = null; iTextSharp.text.Document sourceDocument = null; iTextSharp.text.pdf.PdfCopy pdfCopyProvider = null; iTextSharp.text.pdf.PdfImportedPage importedPage = null; reader = new iTextSharp.text.pdf.PdfReader(path_n_name); sourceDocument = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(startpage)); sourceDocument.Open(); // Creates a .docx to receive the pdf's text Spire.Doc.Document word_doc = new Spire.Doc.Document(); // Word doc formatting Spire.Doc.Section word_doc_section = word_doc.AddSection(); Spire.Doc.Documents.Paragraph word_doc_paragraph = word_doc_section.AddParagraph(); Spire.Doc.Documents.Paragraph word_doc_paragraph_page = word_doc_section.AddParagraph(); // Update those blank pdf files, inserting the copied pages into it try { for (int i = startpage; i <= endpage; i++) { string convi = i.ToString(); pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(pdf_path + "/" + "temp" + "/" + convi + ".pdf", System.IO.FileMode.Append)); sourceDocument.Open(); importedPage = pdfCopyProvider.GetImportedPage(reader, i); pdfCopyProvider.AddPage(importedPage); } sourceDocument.Close(); reader.Close(); } // ERROR catch (Exception ex) { Console.WriteLine("Error! "); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("エラー ! "); throw ex; } // Collects the text without furigana from the listed pdf files switch (caseSwitch) { // case 1 reffers to the left and right alignments of the pdf text case "1": Console.WriteLine(); for (int i = startpage; i <= endpage; i++) { // the following refers to the int counter of pages being converted into string string convi = i.ToString(); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("今のページ: " + convi); Console.WriteLine("Current Page: " + convi); // the following refers to the bitmiracle api pdf to get the texts using (BitMiracle.Docotic.Pdf.PdfDocument pdf_1 = new BitMiracle.Docotic.Pdf.PdfDocument(pdf_path + "/" + "temp" + "/" + convi + ".pdf")) { BitMiracle.Docotic.Pdf.PdfPage page = pdf_1.Pages[0]; foreach (PdfTextData data in page.GetWords()) { if (data.FontSize > 6 && data.Position.X < 600) { string text = data.Text; text.TrimEnd(); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine(text); //word_builder.Writeln(text); word_doc_paragraph.AppendText(text); } } foreach (PdfTextData data in page.GetWords()) { if (data.FontSize > 6 && data.Position.X > 600) { string text = data.Text; text.TrimEnd(); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine(text); word_doc_paragraph.AppendText(text); } } } // the following lines reffers to the space between pages of the pdf text Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); // the followin reffers to the extra lines on word text word_doc_paragraph.AppendText(" "); word_doc_paragraph.AppendText("CURRENT PAGE: " + convi); word_doc_paragraph = word_doc_section.AddParagraph(); word_doc.Sections[0].Paragraphs[i].AppendBreak(BreakType.PageBreak); } break; // case 2 reffers to the alignment of the pdf text that is centralized case "2": Console.WriteLine(); for (int i = startpage; i <= endpage; i++) { // the following refers to the int counter of pages being converted into string string convi = i.ToString(); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("今のページ: " + convi); Console.WriteLine("Current Page: " + convi); // the following refers to the bitmiracle api pdf to get the texts using (BitMiracle.Docotic.Pdf.PdfDocument pdf_1 = new BitMiracle.Docotic.Pdf.PdfDocument(pdf_path + "/" + "temp" + "/" + convi + ".pdf")) { BitMiracle.Docotic.Pdf.PdfPage page = pdf_1.Pages[0]; foreach (PdfTextData data in page.GetWords()) { if (data.FontSize > 6) { string text = data.Text; text.TrimEnd(); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine(text); word_doc_paragraph.AppendText(text); } } } Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); word_doc_paragraph.AppendText(" "); word_doc_paragraph.AppendText("CURRENT PAGE: " + convi); word_doc_paragraph = word_doc_section.AddParagraph(); word_doc.Sections[0].Paragraphs[i].AppendBreak(BreakType.PageBreak); } break; default: Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("error! (エラー)"); Console.ReadKey(); break; } // The following refers to creating a .docx file, opening up the file and deleting the temp folder word_doc.SaveToFile(pdf_path + "/" + pdf_file_name + ".docx", FileFormat.Docx); System.IO.Directory.Delete(pdf_path + "/" + "temp", true); try { System.Diagnostics.Process.Start(pdf_path + "/" + pdf_file_name + ".docx"); } catch { Console.WriteLine("Error! "); Console.OutputEncoding = Encoding.GetEncoding(932); Console.WriteLine("エラー ! "); } }
private void button1_Click(object sender, EventArgs e) { object filename1 = Application.StartupPath + "\\bin\\" + Global.templateName; object G_Missing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document wordDoc; wordDoc = wordApp.Documents.Open(filename1); wordDoc.ActiveWindow.Visible = false;//打开word Microsoft.Office.Interop.Word.Range myRange = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f = myRange.Find; f.Text = "布点数量:"; f.ClearFormatting(); bool finded = f.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange = wordDoc.Range(myRange.End, myRange.End + 6); myRange.Text = textBox1.Text; Microsoft.Office.Interop.Word.Range myRange1 = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f1 = myRange1.Find; f1.Text = "仪表编号:"; f1.ClearFormatting(); bool finded1 = f1.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange1 = wordDoc.Range(myRange1.End, myRange1.End + 9); myRange1.Text = textBox2.Text; Microsoft.Office.Interop.Word.Range myRange2 = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f2 = myRange2.Find; f2.Text = "测量点数量:"; f2.ClearFormatting(); bool finded2 = f2.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange2 = wordDoc.Range(myRange2.End, myRange2.End + 6); myRange2.Text = textBox6.Text; Microsoft.Office.Interop.Word.Range myRange3 = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f3 = myRange3.Find; f3.Text = "仪表编号: "; f3.ClearFormatting(); bool finded3 = f3.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange3 = wordDoc.Range(myRange3.End, myRange3.End + 8); myRange3.Text = textBox5.Text; Microsoft.Office.Interop.Word.Range myRange4 = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f4 = myRange4.Find; f4.Text = "测量点数量: "; f4.ClearFormatting(); bool finded4 = f4.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange4 = wordDoc.Range(myRange4.End, myRange4.End + 5); myRange4.Text = textBox9.Text; Microsoft.Office.Interop.Word.Range myRange5 = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f5 = myRange5.Find; f5.Text = "仪表编号: "; f5.ClearFormatting(); bool finded5 = f5.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange5 = wordDoc.Range(myRange5.End, myRange5.End + 7); myRange5.Text = textBox8.Text; Microsoft.Office.Interop.Word.Range myRange6 = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f6 = myRange6.Find; f6.Text = "测量点数量: "; f6.ClearFormatting(); bool finded6 = f6.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange6 = wordDoc.Range(myRange6.End, myRange6.End + 4); myRange6.Text = textBox12.Text; Microsoft.Office.Interop.Word.Range myRange7 = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f7 = myRange7.Find; f7.Text = "仪表编号: "; f7.ClearFormatting(); bool finded7 = f7.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange7 = wordDoc.Range(myRange7.End, myRange7.End + 6); myRange7.Text = textBox11.Text; Microsoft.Office.Interop.Word.Range myRange8 = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f8 = myRange8.Find; f8.Text = "测量点数量: "; f8.ClearFormatting(); bool finded8 = f8.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange8 = wordDoc.Range(myRange8.End, myRange8.End + 3); myRange8.Text = textBox15.Text; Microsoft.Office.Interop.Word.Range myRange9 = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f9 = myRange9.Find; f9.Text = "仪表编号: "; f9.ClearFormatting(); bool finded9 = f9.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange9 = wordDoc.Range(myRange9.End, myRange9.End + 5); myRange9.Text = textBox14.Text; Microsoft.Office.Interop.Word.Range myRange10 = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f10 = myRange10.Find; f10.Text = "测量点数量: "; f10.ClearFormatting(); bool finded10 = f10.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange10 = wordDoc.Range(myRange10.End, myRange10.End + 2); myRange10.Text = textBox18.Text; Microsoft.Office.Interop.Word.Range myRange11 = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f11 = myRange11.Find; f11.Text = "仪表编号: "; f11.ClearFormatting(); bool finded11 = f11.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange11 = wordDoc.Range(myRange11.End, myRange11.End + 4); myRange11.Text = textBox17.Text; Microsoft.Office.Interop.Word.Range myRange12 = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f12 = myRange12.Find; f12.Text = "测量点数量: "; f12.ClearFormatting(); bool finded12 = f12.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange12 = wordDoc.Range(myRange12.End, myRange12.End + 1); myRange12.Text = textBox21.Text; Microsoft.Office.Interop.Word.Range myRange13 = wordDoc.Range(); Microsoft.Office.Interop.Word.Find f13 = myRange13.Find; f13.Text = "仪表编号: "; f13.ClearFormatting(); bool finded13 = f13.Execute(ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing ); myRange13 = wordDoc.Range(myRange13.End, myRange13.End + 3); myRange13.Text = textBox20.Text; wordDoc.Save(); wordDoc.Close(); wordApp.Quit(); wordApp = null; string ImagePath = pictureBox1.ImageLocation; string strKey = "示意图:(上层,中层,下层)"; object MissingValue = Type.Missing; bool isFindSealLoc = false; Microsoft.Office.Interop.Word.Application wp = null; Microsoft.Office.Interop.Word.Document wd = null; try { wp = new Microsoft.Office.Interop.Word.Application(); wd = wp.Documents.Open(ref filename1, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue); wp.Selection.Find.ClearFormatting(); wp.Selection.Find.Replacement.ClearFormatting(); wp.Selection.Find.Text = strKey; object objReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone; if (wp.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref objReplace, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue)) { object Anchor = wp.Selection.Range; object LinkToFile = false; object SaveWithDocument = true; Microsoft.Office.Interop.Word.InlineShape Inlineshape = wp.Selection.InlineShapes.AddPicture( ImagePath, ref LinkToFile, ref SaveWithDocument, ref Anchor); Inlineshape.Select(); Microsoft.Office.Interop.Word.Shape shape = Inlineshape.ConvertToShape(); shape.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind; isFindSealLoc = true; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { if (wd != null) { wd.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wd); wd = null; } if (wp != null) { wp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wp); wp = null; } } string ImagePath1 = pictureBox2.ImageLocation; string strKey1 = "6.1.2风机出风口布点"; object MissingValue1 = Type.Missing; bool isFindSealLoc1 = false; Microsoft.Office.Interop.Word.Application wp1 = null; Microsoft.Office.Interop.Word.Document wd1 = null; try { wp1 = new Microsoft.Office.Interop.Word.Application(); wd1 = wp1.Documents.Open(ref filename1, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue); wp1.Selection.Find.ClearFormatting(); wp1.Selection.Find.Replacement.ClearFormatting(); wp1.Selection.Find.Text = strKey1; object objReplace1 = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone; if (wp1.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref objReplace1, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue)) { object Anchor1 = wp1.Selection.Range; object LinkToFile1 = false; object SaveWithDocument1 = true; Microsoft.Office.Interop.Word.InlineShape Inlineshape1 = wp1.Selection.InlineShapes.AddPicture( ImagePath1, ref LinkToFile1, ref SaveWithDocument1, ref Anchor1); Inlineshape1.Select(); Microsoft.Office.Interop.Word.Shape shape1 = Inlineshape1.ConvertToShape(); shape1.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind; isFindSealLoc1 = true; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { if (wd1 != null) { wd1.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wd1); wd1 = null; } if (wp1 != null) { wp1.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wp1); wp1 = null; } } string ImagePath2 = pictureBox3.ImageLocation; string strKey2 = "6.1.3出入口布点"; object MissingValue2 = Type.Missing; bool isFindSealLoc2 = false; Microsoft.Office.Interop.Word.Application wp2 = null; Microsoft.Office.Interop.Word.Document wd2 = null; try { wp2 = new Microsoft.Office.Interop.Word.Application(); wd2 = wp2.Documents.Open(ref filename1, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue); wp2.Selection.Find.ClearFormatting(); wp2.Selection.Find.Replacement.ClearFormatting(); wp2.Selection.Find.Text = strKey2; object objReplace2 = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone; if (wp2.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref objReplace2, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue)) { object Anchor2 = wp2.Selection.Range; object LinkToFile2 = false; object SaveWithDocument2 = true; Microsoft.Office.Interop.Word.InlineShape Inlineshape2 = wp2.Selection.InlineShapes.AddPicture( ImagePath2, ref LinkToFile2, ref SaveWithDocument2, ref Anchor2); Inlineshape2.Select(); Microsoft.Office.Interop.Word.Shape shape2 = Inlineshape2.ConvertToShape(); shape2.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind; isFindSealLoc2 = true; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { if (wd2 != null) { wd2.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wd2); wd2 = null; } if (wp2 != null) { wp2.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wp2); wp2 = null; } } string ImagePath3 = pictureBox4.ImageLocation; string strKey3 = "6.1.4死角布点"; object MissingValue3 = Type.Missing; bool isFindSealLoc3 = false; Microsoft.Office.Interop.Word.Application wp3 = null; Microsoft.Office.Interop.Word.Document wd3 = null; try { wp3 = new Microsoft.Office.Interop.Word.Application(); wd3 = wp3.Documents.Open(ref filename1, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue); wp3.Selection.Find.ClearFormatting(); wp3.Selection.Find.Replacement.ClearFormatting(); wp3.Selection.Find.Text = strKey3; object objReplace3 = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone; if (wp3.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref objReplace3, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue)) { object Anchor3 = wp3.Selection.Range; object LinkToFile3 = false; object SaveWithDocument3 = true; Microsoft.Office.Interop.Word.InlineShape Inlineshape3 = wp3.Selection.InlineShapes.AddPicture( ImagePath3, ref LinkToFile3, ref SaveWithDocument3, ref Anchor3); Inlineshape3.Select(); Microsoft.Office.Interop.Word.Shape shape3 = Inlineshape3.ConvertToShape(); shape3.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind; isFindSealLoc3 = true; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { if (wd3 != null) { wd3.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wd3); wd3 = null; } if (wp3 != null) { wp3.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wp3); wp3 = null; } } string ImagePath4 = pictureBox5.ImageLocation; string strKey4 = "6.1.5死角布点"; object MissingValue4 = Type.Missing; bool isFindSealLoc4 = false; Microsoft.Office.Interop.Word.Application wp4 = null; Microsoft.Office.Interop.Word.Document wd4 = null; try { wp4 = new Microsoft.Office.Interop.Word.Application(); wd4 = wp4.Documents.Open(ref filename1, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue); wp4.Selection.Find.ClearFormatting(); wp4.Selection.Find.Replacement.ClearFormatting(); wp4.Selection.Find.Text = strKey4; object objReplace4 = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone; if (wp4.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref objReplace4, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue)) { object Anchor4 = wp4.Selection.Range; object LinkToFile4 = false; object SaveWithDocument4 = true; Microsoft.Office.Interop.Word.InlineShape Inlineshape4 = wp4.Selection.InlineShapes.AddPicture( ImagePath4, ref LinkToFile4, ref SaveWithDocument4, ref Anchor4); Inlineshape4.Select(); Microsoft.Office.Interop.Word.Shape shape4 = Inlineshape4.ConvertToShape(); shape4.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind; isFindSealLoc4 = true; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { if (wd4 != null) { wd4.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wd4); wd4 = null; } if (wp4 != null) { wp4.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wp4); wp4 = null; } } string ImagePath5 = pictureBox6.ImageLocation; string strKey5 = "6.1.6货架布点"; object MissingValue5 = Type.Missing; bool isFindSealLoc5 = false; Microsoft.Office.Interop.Word.Application wp5 = null; Microsoft.Office.Interop.Word.Document wd5 = null; try { wp5 = new Microsoft.Office.Interop.Word.Application(); wd5 = wp5.Documents.Open(ref filename1, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue); wp5.Selection.Find.ClearFormatting(); wp5.Selection.Find.Replacement.ClearFormatting(); wp5.Selection.Find.Text = strKey5; object objReplace5 = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone; if (wp5.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref objReplace5, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue)) { object Anchor5 = wp5.Selection.Range; object LinkToFile5 = false; object SaveWithDocument5 = true; Microsoft.Office.Interop.Word.InlineShape Inlineshape5 = wp5.Selection.InlineShapes.AddPicture( ImagePath5, ref LinkToFile5, ref SaveWithDocument5, ref Anchor5); Inlineshape5.Select(); Microsoft.Office.Interop.Word.Shape shape5 = Inlineshape5.ConvertToShape(); shape5.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind; isFindSealLoc5 = true; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { if (wd5 != null) { wd5.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wd5); wd5 = null; } if (wp5 != null) { wp5.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wp5); wp5 = null; } } string ImagePath6 = pictureBox7.ImageLocation; string strKey6 = "6.1.7监控系统探头及验证环境布点"; object MissingValue6 = Type.Missing; bool isFindSealLoc6 = false; Microsoft.Office.Interop.Word.Application wp6 = null; Microsoft.Office.Interop.Word.Document wd6 = null; try { wp6 = new Microsoft.Office.Interop.Word.Application(); wd6 = wp6.Documents.Open(ref filename1, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue); wp6.Selection.Find.ClearFormatting(); wp6.Selection.Find.Replacement.ClearFormatting(); wp6.Selection.Find.Text = strKey6; object objReplace6 = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone; if (wp6.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref objReplace6, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue)) { object Anchor6 = wp6.Selection.Range; object LinkToFile6 = false; object SaveWithDocument6 = true; Microsoft.Office.Interop.Word.InlineShape Inlineshape6 = wp6.Selection.InlineShapes.AddPicture( ImagePath6, ref LinkToFile6, ref SaveWithDocument6, ref Anchor6); Inlineshape6.Select(); Microsoft.Office.Interop.Word.Shape shape6 = Inlineshape6.ConvertToShape(); shape6.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind; isFindSealLoc6 = true; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { if (wd6 != null) { wd6.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wd6); wd6 = null; } if (wp6 != null) { wp6.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wp6); wp6 = null; } MessageBox.Show("导入成功!"); } #region 除后台word占用。 System.Diagnostics.Process myproc = new System.Diagnostics.Process(); //得到所有打开的进程 try { foreach (Process thisproc in Process.GetProcessesByName("WINWORD")) { if (!thisproc.CloseMainWindow()) { thisproc.Kill(); } } } catch (Exception) { MessageBox.Show("杀死" + "WINWORD" + "失败!"); } #endregion string filename = Environment.CurrentDirectory.ToString() + "\\bin\\" + Global.templateName + ".doc"; Spire.Doc.Document document = new Spire.Doc.Document(filename, FileFormat.Docx); Spire.Doc.Fields.TextBox textBox = document.TextBoxes[2]; Spire.Doc.Documents.Paragraph paragraph = textBox.Body.AddParagraph(); Spire.Doc.Fields.TextRange textRange = paragraph.AppendText(textBox3.Text); document.SaveToFile(filename, FileFormat.Docx); Spire.Doc.Fields.TextBox textBox111 = document.TextBoxes[3]; Spire.Doc.Documents.Paragraph paragraph1 = textBox111.Body.AddParagraph(); Spire.Doc.Fields.TextRange textRange1 = paragraph1.AppendText(textBox4.Text); document.SaveToFile(filename, FileFormat.Docx); Spire.Doc.Fields.TextBox textBox22 = document.TextBoxes[4]; Spire.Doc.Documents.Paragraph paragraph2 = textBox22.Body.AddParagraph(); Spire.Doc.Fields.TextRange textRange2 = paragraph2.AppendText(textBox7.Text); document.SaveToFile(filename, FileFormat.Docx); Spire.Doc.Fields.TextBox textBox33 = document.TextBoxes[5]; Spire.Doc.Documents.Paragraph paragraph33 = textBox33.Body.AddParagraph(); Spire.Doc.Fields.TextRange textRange33 = paragraph33.AppendText(textBox10.Text); document.SaveToFile(filename, FileFormat.Docx); Spire.Doc.Fields.TextBox textBox55 = document.TextBoxes[6]; Spire.Doc.Documents.Paragraph paragraph5 = textBox55.Body.AddParagraph(); Spire.Doc.Fields.TextRange textRange5 = paragraph5.AppendText(textBox13.Text); document.SaveToFile(filename, FileFormat.Docx); Spire.Doc.Fields.TextBox textBox66 = document.TextBoxes[7]; Spire.Doc.Documents.Paragraph paragraph6 = textBox66.Body.AddParagraph(); Spire.Doc.Fields.TextRange textRange6 = paragraph6.AppendText(textBox16.Text); document.SaveToFile(filename, FileFormat.Docx); Spire.Doc.Fields.TextBox textBox88 = document.TextBoxes[8]; Spire.Doc.Documents.Paragraph paragraph8 = textBox88.Body.AddParagraph(); Spire.Doc.Fields.TextRange textRange8 = paragraph8.AppendText(textBox19.Text); document.SaveToFile(filename, FileFormat.Docx); MessageBox.Show("导入成功!"); this.Close(); }
private void Button4_Click(object sender, EventArgs e) { DataTable dt = (DataTable)dataGridView1.DataSource; bool IsExistEmail = false; bool IsExistcontactperson = false; foreach (DataColumn col in dt.Columns) { if (col.ColumnName == "EMAIL") { IsExistEmail = true; } } foreach (DataColumn col in dt.Columns) { if (col.ColumnName == "CONTACT PERSON") { IsExistcontactperson = true; } } StringBuilder sb = new StringBuilder(); if (dt != null && IsExistEmail == true && IsExistcontactperson == true) { try { // listView1.Items.Clear(); foreach (DataRow row in dt.Rows) { var ResultName = textBox2.Text + "\\" + string.Format(@"email{0}.docx", DateTime.Now.Ticks); Document document = new Document(); document.LoadFromFile(textBox2.Text + "\\" + comboBox2.Text); String contactPerson = row["contact person".ToUpper()].ToString(); document.Replace("<contact person>", contactPerson, false, true); document.SaveToFile(ResultName, FileFormat.Docx); // System.Diagnostics.Process.Start("Replace.docx"); // dotx2docx("demo.dotx", ResultName); // Mailmerge(ResultName, row, dt.Columns); // String contactPerson = row["contact person".ToUpper()].ToString(); String Toemail = row["email".ToUpper()].ToString(); MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient(txtHost.Text); System.Text.Encoding SystemEncoding; SystemEncoding = System.Text.Encoding.UTF8; mail.From = new MailAddress(txtForm.Text); mail.To.Add(Toemail); mail.Subject = txtSubjec.Text; mail.IsBodyHtml = true; System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment(ResultName); mail.Attachments.Add(attachment); mail.Body = settings.Body; // GetTemplate("EmailDetial.txt").Replace("<contact person>", contactPerson); SmtpServer.Port = Convert.ToInt32(settings.Port); String Name = txtName.Text; String password = txtPassword.Text; SmtpServer.Credentials = new System.Net.NetworkCredential(Name, password); if (settings.Encryption == "SSL") { SmtpServer.EnableSsl = true; } else if (settings.Encryption == "") { SmtpServer.EnableSsl = false; } SmtpServer.Send(mail); sb.Append(contactPerson + "--> " + Toemail + " is sent" + System.Environment.NewLine); //MessageBox.Show("mail Send"); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); toolStripStatusLabel1.Text = (ex.ToString()); } } else { if (IsExistcontactperson == false) { toolStripStatusLabel1.Text = ("Missing contact person column in csv file"); } if (IsExistEmail == false) { toolStripStatusLabel1.Text = ("Missing contact email column in csv file"); } } textBox1.Text = sb.ToString(); }