private static void AddAttachment(ref Outlook.MailItem email, Word.Document wDoc, RenderSettings.MediaType mediaType, string attachName, ref List <string> tempFiles) { if (wDoc == null || email == null) { return; } string filePath = string.IsNullOrEmpty(attachName) ? wDoc.FullName : attachName + FileExtension.Xml; // mwxml object missing = System.Type.Missing; switch (mediaType) { case RenderSettings.MediaType.Docx: // msxml filePath = AssetManager.FileAdapter.GetFilePath( string.Format("{0}\\{1}", AssetManager.FileAdapter.TemporaryFolderPath, System.IO.Path.GetFileNameWithoutExtension(filePath)), FileExtension.Docx); // msxml wDoc.SaveAs(filePath, Word.WdSaveFormat.wdFormatXMLDocument); tempFiles.Add(filePath); break; case RenderSettings.MediaType.Pdf: filePath = AssetManager.FileAdapter.GetFilePath( string.Format("{0}\\{1}", AssetManager.FileAdapter.TemporaryFolderPath, System.IO.Path.GetFileNameWithoutExtension(filePath)), FileExtension.Pdf); wDoc.ExportAsFixedFormat(filePath, Word.WdExportFormat.wdExportFormatPDF); tempFiles.Add(filePath); break; case RenderSettings.MediaType.Xps: filePath = AssetManager.FileAdapter.GetFilePath( string.Format("{0}\\{1}", AssetManager.FileAdapter.TemporaryFolderPath, System.IO.Path.GetFileNameWithoutExtension(filePath)), FileExtension.Xps); wDoc.ExportAsFixedFormat(filePath, Word.WdExportFormat.wdExportFormatXPS); tempFiles.Add(filePath); break; default: filePath = string.Empty; break; } if (!string.IsNullOrEmpty(filePath) && System.IO.File.Exists(filePath)) { email.Attachments.Add(filePath, missing, missing, missing); } }
public static void ConvertToPDF(String filePath, String destpath) { // file exist & check type if (!filePath.IsNormalized() || !File.Exists(filePath)) { throw new Exception("未指定文件"); } if (!filePath.EndsWith("doc") && !filePath.EndsWith("docx")) { throw new Exception("文件非 word 类型"); } Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass(); Microsoft.Office.Interop.Word.Document doc = word.Documents.Open(filePath); doc.ExportAsFixedFormat(destpath, WdExportFormat.wdExportFormatPDF); // rename List <String> list = new List <string>(); String[] fileNames = Directory.GetFiles(destpath); foreach (var fileName in fileNames) { String newFileName = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName) + Path.GetExtension(fileName)); File.Move(fileName, newFileName); list.Add(newFileName); } }
private static byte[] ConvertWordToPDF(byte[] dataWord) { byte[] dataPDF = null; Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application(); string tmpFileWord = Path.GetTempFileName(); FileStream tmpFileStream = File.OpenWrite(tmpFileWord); tmpFileStream.Write(dataWord, 0, dataWord.Length); tmpFileStream.Close(); Microsoft.Office.Interop.Word.Document wordDocument = appWord.Documents.Open(tmpFileWord); string tmpFilePDF = Path.GetTempFileName(); wordDocument.ExportAsFixedFormat(tmpFilePDF, WdExportFormat.wdExportFormatPDF); using (FileStream fs = new FileStream(tmpFilePDF, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { fs.Position = 0; dataPDF = new BinaryReader(fs).ReadBytes(int.Parse(fs.Length.ToString())); fs.Position = 0; } return(dataPDF); }
/// <summary> /// word to pdf /// </summary> /// <param name="infile"></param> /// <param name="outfile"></param> /// <returns></returns> public static bool wordtopdf(string infile, string outfile) { wd.Application application = null; wd.Document document = null; try { application = new wd.Application(); application.Visible = false; document = application.Documents.Open(infile); document.ExportAsFixedFormat(outfile, wd.WdExportFormat.wdExportFormatPDF); return(true); } catch (Exception ex) { copyto(infile); return(false); } finally { if (document != null) { document.Close(); document = null; } if (application != null) { application.Quit(); application = null; } } }
public void SaveFileDocToPdf(string pathFilePdf, string fileDoc, bool closeFile) { try { OpendFileDOC(fileDoc, false); if (doc != null) { if (fileDoc.ToLower().IndexOf(".docx") != -1) { doc.ExportAsFixedFormat(pathFilePdf, paramExportFormat, paramOpenAfterExport, paramExportOptimizeFor, paramWdExportRange, paramFromPage, paramToPage, paramWdExportItem, paramIncludeDocProps, paramKeepIRM, paramWdExportCreateBookmarks, paramDocStruc, paramBitmapMissingFont, paramUseISO19005, ref objMiss); } //else // xlWorkbook.SaveAs(fileExcel, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); //xlWorkbook.Saved = true; } if (closeFile) //Đóng tập tin lại { CloseFileDOC(); } } catch { if (closeFile) { CloseFileDOC(); } } }
/// <summary> /// 转换word 成PDF文档 /// </summary> /// <param name="_lstrInputFile">原文件路径</param> /// <param name="_lstrOutFile">pdf文件输出路径</param> /// <returns>true 成功</returns> public static bool ConvertWordToPdf(string _lstrInputFile, string _lstrOutFile) { Microsoft.Office.Interop.Word.Application application = null; Word.Document document = null; try { application = new Microsoft.Office.Interop.Word.Application(); application.Visible = false; document = application.Documents.Open(_lstrInputFile); document.ExportAsFixedFormat(_lstrOutFile, Word.WdExportFormat.wdExportFormatPDF); return(true); } catch (Exception ex) { return(false); } finally { if (document != null) { document.Close(); } if (application != null) { application.Quit(); } } }
public bool WordToPDF2(string sourcePath) { bool result = false; Application application = new Application(); Microsoft.Office.Interop.Word.Document document = null; try { application.Visible = false; document = application.Documents.Open(sourcePath); string PDFPath = sourcePath.Replace(".doc", ".pdf"); //pdf存放位置 if (!File.Exists(PDFPath)) //存在PDF,不需要继续转换 { document.ExportAsFixedFormat(PDFPath, WdExportFormat.wdExportFormatPDF); } result = true; } catch (Exception e) { Console.WriteLine(e.Message); result = false; } finally { document.Close(); } return(result); }
private void Form1_Load(object sender, EventArgs e) { try { app = new Microsoft.Office.Interop.Word.Application(); doc = app.Documents.Open(ref fileLocation, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss); this.FindAndReplace("[nombre]", nombrePaciente); this.FindAndReplace("[edad]", Convert.ToString(edadPaciete)); this.FindAndReplace("[sexo]", sexoPaciente); this.FindAndReplace("[fechaIngreso]", Convert.ToString(fechaIngreso)); this.FindAndReplace("[motivo]", motivoConsulta); this.FindAndReplace("[HEA]", HEA); this.FindAndReplace("[antecedentes]", Antecedentes); this.FindAndReplace("[historial]", examenFisico); this.FindAndReplace("[clave]", clave); this.FindAndReplace("[enfermedad]", enfermedad); this.FindAndReplace("[tratamiento]", Tratamiento); doc.ExportAsFixedFormat(tmpFile.ToString(), Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF); this.pdfReport.src = tmpFile.ToString(); this.pdfReport.Show(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { doc.Close(WdSaveOptions.wdDoNotSaveChanges, WdOriginalFormat.wdOriginalDocumentFormat, false); app.Quit(WdSaveOptions.wdDoNotSaveChanges); } }
private void btn_send_Click(object sender, EventArgs e) { //create a temp folder to put the pdf in Directory.CreateDirectory(tempFolder); Trace.WriteLine("Here's where the temp folder is: " + tempFolder.ToString()); //store the document as a pdf in the temp location string sfileName = doc.Name.Substring(0, doc.Name.Length - 5); //remove the .docx file extension string sFullpath_pdf = tempFolder + "\\" + sfileName + ".pdf"; doc.ExportAsFixedFormat(sFullpath_pdf, Word.WdExportFormat.wdExportFormatPDF, OpenAfterExport: false); // you'll need a doc range here //create a new mail Outlook.Application OutlookApp = new Outlook.Application(); Outlook.MailItem mail = (Outlook.MailItem)OutlookApp.CreateItem(Outlook.OlItemType.olMailItem); mail.To = txt_email.Text; mail.Subject = "CAMS form"; mail.Body = "Here is the form from your last session."; mail.Attachments.Add(sFullpath_pdf); mail.Display(true); //show the new Mail File.Delete(sFullpath_pdf); Trace.WriteLine("I deleted the files"); //TODO: figure out how to also delete the directory... }
public static bool WordToPDF(string sourcePath, string targetPath) { bool result = false; Microsoft.Office.Interop.Word.WdExportFormat exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF; Microsoft.Office.Interop.Word.Application application = null; Microsoft.Office.Interop.Word.Document document = null; object unknow = System.Type.Missing; application = new Microsoft.Office.Interop.Word.Application(); application.Visible = false; document = application.Documents.Open(sourcePath); document.SaveAs(); document.ExportAsFixedFormat(targetPath, exportFormat, false); //document.ExportAsFixedFormat(targetPath, exportFormat); result = true; //application.Documents.Close(ref unknow, ref unknow, ref unknow); document.Close(ref unknow, ref unknow, ref unknow); document = null; application.Quit(); //application.Quit(ref unknow, ref unknow, ref unknow); application = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); return(result); }
private static string DocxToPdf(string filePath, bool withBookmark) { if (!File.Exists(filePath)) { Console.WriteLine("文件" + filePath + "不存在"); return(null); } MSWord.Application app = new MSWord.Application { Visible = false }; MSWord.Document doc = app.Documents.Open(filePath); string dest = GetDestFilename(filePath); doc.ExportAsFixedFormat(dest, MSWord.WdExportFormat.wdExportFormatPDF, CreateBookmarks: withBookmark ? MSWord.WdExportCreateBookmarks.wdExportCreateHeadingBookmarks : MSWord.WdExportCreateBookmarks.wdExportCreateNoBookmarks); doc.Close(); app.Quit(); return(dest); }
public bool ConvertWordToPdf(string inputFile, string outputfile) { Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document wordDoc = null; object inputFileTemp = inputFile; try { wordDoc = wordApp.Documents.Open(inputFile); wordDoc.ExportAsFixedFormat(outputfile, WdExportFormat.wdExportFormatPDF); } catch (Exception) { MessageBox.Show("Co loi xay ra"); return(false); } finally { if (wordDoc != null) { wordDoc.Close(WdSaveOptions.wdDoNotSaveChanges); } if (wordApp != null) { wordApp.Quit(WdSaveOptions.wdDoNotSaveChanges); wordApp = null; } } return(true); }
private bool ConvertDocToPdf(string tempPath, string outputPath) { // For opening ext: DOC and similar word extensions Application appWord = null; Document wordDocument = null; if (string.IsNullOrEmpty(tempPath) || string.IsNullOrEmpty(outputPath)) { return(false); } try { appWord = new Application(); wordDocument = appWord.Documents.Open(tempPath); wordDocument.ExportAsFixedFormat(outputPath, WdExportFormat.wdExportFormatPDF); return(true); } catch (Exception ex) { Console.WriteLine(ex); return(false); } finally { if (wordDocument != null) { wordDocument.Close(false); } if (appWord != null) { appWord.NormalTemplate.Saved = true; appWord.Quit(false); } } }
public static void SaveDocumentAsPDF(Word.Document document, string targetPath) { if (Path.GetExtension(targetPath).ToUpper() != "PDF") { targetPath = Path.Combine(Path.GetDirectoryName(targetPath), string.Concat(Path.GetFileNameWithoutExtension(targetPath), ".pdf")); } try { if (File.Exists(targetPath)) { File.Delete(targetPath); } Word.WdExportFormat exportFormat = Word.WdExportFormat.wdExportFormatPDF; bool openAfterExport = false; Word.WdExportOptimizeFor exportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForPrint; Word.WdExportRange exportRange = Word.WdExportRange.wdExportAllDocument; int startPage = 0; int endPage = 0; Word.WdExportItem exportItem = Word.WdExportItem.wdExportDocumentContent; bool includeDocProps = false; bool keepIRM = true; Word.WdExportCreateBookmarks createBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks; bool docStructureTags = true; bool bitmapMissingFonts = true; //11/05/2017 bool useISO19005_1 = true; object missing = Missing.Value; // Export it in the specified format. if (document != null) { document.ExportAsFixedFormat( targetPath, exportFormat, openAfterExport, exportOptimizeFor, exportRange, startPage, endPage, exportItem, includeDocProps, keepIRM, createBookmarks, docStructureTags, bitmapMissingFonts, useISO19005_1, ref missing); } } catch (System.IO.IOException ex) { logger.LogException(LogLevel.Error, "SaveDocumentAsPDF", ex); throw ex; } catch (Exception ex) { logger.LogException(LogLevel.Error, "SaveDocumentAsPDF", ex); } }
public override void Convert(String inputFile, String outputFile) { Object nothing = System.Reflection.Missing.Value; try { if (!File.Exists(inputFile)) { throw new ConvertException("File not Exists"); } if (IsPasswordProtected(inputFile)) { throw new ConvertException("Password Exist"); } app = new Word.Application(); docs = app.Documents; doc = docs.Open(inputFile, false, true, false, nothing, nothing, true, nothing, nothing, nothing, nothing, false, false, nothing, true, nothing); doc.ExportAsFixedFormat(outputFile, Word.WdExportFormat.wdExportFormatPDF, false, Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument, 1, 1, Word.WdExportItem.wdExportDocumentContent, false, false, Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks, false, false, false, nothing); } catch (Exception e) { release(); throw new ConvertException(e.Message); } release(); }
public void Export(string path, string type) { if (string.IsNullOrEmpty(type)) { type = path.Split('.').LastOrDefault(); } try { string outPath = string.IsNullOrEmpty(path) ? this.path : path; Word.WdExportFormat format; switch (type.ToLower()) { case "pdf": format = Word.WdExportFormat.wdExportFormatPDF; break; case "xps": format = Word.WdExportFormat.wdExportFormatXPS; break; default: throw new ApplicationException("Unknown format type"); } document.ExportAsFixedFormat(path, format); } catch (Exception) { throw; } }
private void btn_Save_As_Pdf(object sender, RibbonControlEventArgs e) { string sfilepath = ""; //获取pdf保存路劲 if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK) { if (this.folderBrowserDialog1.SelectedPath.Trim() != "") { sfilepath = this.folderBrowserDialog1.SelectedPath.Trim(); } else { MessageBox.Show("路径无效"); return; } } else { return; } //获取当前文档 Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument; string sfileName_Document = doc.Name; doc.ExportAsFixedFormat(sfilepath, Word.WdExportFormat.wdExportFormatPDF, true); }
public void doc() { bool result = false; Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document document = null; try { application.Visible = false; document = application.Documents.Open(@"C:\Users\18518\Documents\1.docx"); string PDFPath = AppDomain.CurrentDomain.BaseDirectory + "1.pdf"; //pdf存放位置 if (!System.IO.File.Exists(@PDFPath)) //存在PDF,不需要继续转换 { document.ExportAsFixedFormat(PDFPath, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF, CreateBookmarks: WdExportCreateBookmarks.wdExportCreateWordBookmarks); } result = true; } catch (Exception e) { Console.WriteLine(e.Message); result = false; } finally { //document.Close(); } }
public override void Convert(String inputFile, String outputFile) { Object nothing = System.Reflection.Missing.Value; try { if (!File.Exists(inputFile)) { throw new ConvertException("File not Exists"); } if (IsPasswordProtected(inputFile)) { throw new ConvertException("Password Exist"); } app = new Word.Application(); docs = app.Documents; doc = docs.Open(inputFile, false, true, false, nothing, nothing, true, nothing, nothing, nothing, nothing, false, false, nothing, true, nothing); doc.ExportAsFixedFormat(outputFile, Word.WdExportFormat.wdExportFormatPDF, false, Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument, 1, 1, Word.WdExportItem.wdExportDocumentContent, false, false, Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks, false, false, false, nothing); } catch (Exception e) { release(); throw new ConvertException(e.Message); } release(); }
public async Task <dynamic> GetWord(dynamic opts) { string file = Path.GetFullPath(opts.input as string); string pdfFile = Path.GetFullPath(opts.output as string); return(await this.scheduler.StartNew(() => { Thread.Sleep(100); CreateWord(); Word.Document doc = this.msword.Documents.OpenNoRepairDialog(file, false, true, false, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, false, true, Type.Missing, true, Type.Missing); Delay(0); try { Delay(1); doc.ExportAsFixedFormat(pdfFile, Word.WdExportFormat.wdExportFormatPDF); Delay(2); } finally { (doc as Word._Document).Close(false); Marshal.ReleaseComObject(doc); } //closeInternal(); return pdfFile; })); }
public void ConverterDocumento(string filePath, string path) { object missing = Type.Missing; //Abre a aplicação Word e faz uma cópia do documento mapeado Microsoft.Office.Interop.Word.Application oApp = new Microsoft.Office.Interop.Word.Application(); object template = filePath; Microsoft.Office.Interop.Word.Document oDoc = oApp.Documents.Add(ref template, ref missing, ref missing, ref missing); oDoc.ExportAsFixedFormat(path, WdExportFormat.wdExportFormatPDF); oDoc.Close(false); // Close the Word Document. oApp.Quit(false); // Close Word Application. // Release all Interop objects. if (oDoc != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc); } if (oApp != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oApp); } oDoc = null; oApp = null; GC.Collect(); }
public static bool OfficeWordToPDF(string sourcePath, string targetPath) { bool result = false; Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document document = null; try { //application.ScreenUpdating = true; application.Visible = false; document = application.Documents.Open(sourcePath); document.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF); result = true; } catch (Exception e) { Console.WriteLine(e.Message); result = false; } finally { document.Close(); } return(result); }
public void Word2Pdf(string path, string outputPath) { Word.Application wordApp = new Word.Application(); Word.Document wordDocument = wordApp.Documents.Open(path); wordDocument.ExportAsFixedFormat(outputPath, Word.WdExportFormat.wdExportFormatPDF); wordDocument.Close(); }
void crearImg(Word.Document wordDoc, Profesor p) { wordDoc.ExportAsFixedFormat(@Application.StartupPath.ToString() + "\\aux1.pdf", Word.WdExportFormat.wdExportFormatPDF); wordDoc.Close(); File.Delete(@Application.StartupPath.ToString() + "\\aux1.docx"); }
private void JsonToDocument(string jsonData, string templateFileName, string outputFolderName, string outputFileName) { object sourcefile = templateFileName; string tempWordFileName = TEMPORARY_FILE_FOLDER_PATH + outputFileName.Split('.')[0].ToString() + ".docx"; string outputPDFFilePath = outputFolderName + outputFileName; var jsonLinq = JObject.Parse(jsonData); IList <string> keys = jsonLinq.Properties().Select(p => p.Name).ToList(); object missing = Type.Missing; object oFalse = false; object oTrue = true; Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref sourcefile, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); doc.Activate(); foreach (string key in keys) { //If key is a property if (jsonLinq[key].GetType().ToString() == "Newtonsoft.Json.Linq.JValue") { FindAndReplaceText(doc, key, jsonLinq[key].ToString()); } //if key is a collection else if (jsonLinq[key].GetType().ToString() == "Newtonsoft.Json.Linq.JArray") { var collection = jsonLinq[key].ToArray(); AddTableToDocument(doc, key, collection); } } AddImageToDocument(doc); if (System.IO.File.Exists(tempWordFileName)) { System.IO.File.Delete(tempWordFileName); } doc.SaveAs(tempWordFileName); if (System.IO.File.Exists(outputPDFFilePath)) { System.IO.File.Delete(outputPDFFilePath); } doc.ExportAsFixedFormat(outputPDFFilePath, WdExportFormat.wdExportFormatPDF); doc.Close(ref missing, ref missing, ref missing); wordApp.Quit(ref missing, ref missing, ref missing); if (System.IO.File.Exists(tempWordFileName)) { System.IO.File.Delete(tempWordFileName); } }
static void Main(string[] args) { var docUrl = ConfigurationManager.AppSettings["docUrl"]; var pdfUrl = ConfigurationManager.AppSettings["PdfUrl"]; Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application(); wordDocument = appWord.Documents.Open(@docUrl); wordDocument.ExportAsFixedFormat(@pdfUrl, WdExportFormat.wdExportFormatPDF); }
//clicking on the Save as PDF button private void btn_PDF_Click(object sender, EventArgs e) { //string sfileName_Document = doc.Name; string sfileName = doc.Name.Substring(0, doc.Name.Length - 5); //remove the .docx file extension string sPath = doc.Path; string sFullpath_pdf = sPath + "\\" + sfileName + ".pdf"; doc.ExportAsFixedFormat(sFullpath_pdf, Word.WdExportFormat.wdExportFormatPDF, OpenAfterExport: true); }
public void SaveAndClose(string outputPath) { string pdfOutputFormatPath = $"{outputPath.Replace("docx","pdf")}"; Document.SaveAs2(outputPath); Document.ExportAsFixedFormat(pdfOutputFormatPath, Word.WdExportFormat.wdExportFormatPDF, false, Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen); Document.Close(false); Marshal.ReleaseComObject(Document); }
public byte[] ConvertToPDF(byte[] data, string extention) { var dataDosya = @"C:\Document"; var pdfDosya = @"C:\PDF"; Random rnd = new Random(); int randomSayi = rnd.Next(111111); string dosyaPathdata = dataDosya + @"\" + randomSayi + "." + extention; string dosyapathPdf = pdfDosya + @"\" + randomSayi + ".pdf"; File.WriteAllBytes(dosyaPathdata, data); if (extention == "xlsx") { Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); app.Visible = false; Microsoft.Office.Interop.Excel.Workbook wkb = app.Workbooks.Open(dosyaPathdata, ReadOnly: true); wkb.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, dosyapathPdf); wkb.Close(); app.Quit(); } else if (extention == "doc" || extention == "docx") { Microsoft.Office.Interop.Word.Application wApp = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document wordDoc = null; object inputFileTemp = dosyaPathdata; wordDoc = wApp.Documents.Open(dosyaPathdata); wordDoc.ExportAsFixedFormat(dosyapathPdf, WdExportFormat.wdExportFormatPDF); wordDoc.Close(); wApp.Quit(); } var pdfByte = File.ReadAllBytes(pdfDosya + @"\" + randomSayi + ".pdf"); if (File.Exists(dosyaPathdata)) { try { File.Delete(dosyaPathdata); } catch (Exception) { throw; } } //if (File.Exists(dosyapathPdf)) //{ // try // { // File.Delete(dosyapathPdf); // } // catch (Exception) // { // throw; // } //} return(pdfByte); }
public void ConvertDocxToPdf(Word.Document CurrentWordDocument) { GetDefaultPdfName(CurrentWordDocument.Path, CurrentWordDocument.Name); if (_saveDialog.ShowDialog() == DialogResult.OK) { _saveAsPdfPath = _saveDialog.FileName; CurrentWordDocument.ExportAsFixedFormat(_saveAsPdfPath, Word.WdExportFormat.wdExportFormatPDF); } }
private void btn_Save_to_PDF_Click(object sender, RibbonControlEventArgs e) { Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument; string sfileName_Document = doc.Name.Substring(0, doc.Name.Length - 5); string sPath = doc.Path; string sFullpath_pdf = sPath + "\\" + sfileName_Document + ".pdf"; doc.ExportAsFixedFormat(sFullpath_pdf, Word.WdExportFormat.wdExportFormatPDF, OpenAfterExport: true); }
public void datosaword2(object sender, DoWorkEventArgs e) { CreandoInterna = true; ListaCodigos = new List<CamposCodigos>(); CamposCodigos CampoCodigo; try { matarProcesosWordExcel(); int ContadorEtiquetas = 1; foreach (KeyValuePair<int, int> TipyVarEtqs in TodasLasEtiquetasFinales) { File.Copy(@rutasEnModAdmin.RutaDePlantillas + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx", @rutasEnModAdmin.RutaDeTemp + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx"); appWord = new Word.Application(); appWord.Visible = false; bool bandera = false; doc = appWord.Documents.Open(@rutasEnModAdmin.RutaDeTemp + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx"); foreach (Word.Shape s in doc.Shapes) { bandera = false; if (s.Type.ToString() == "msoTextBox") { s.Name = s.Name.Trim(); if (s.Name == "txtC1") { s.TextFrame.TextRange.Text = ""; continue; } if (s.Name == "txtC2") { s.TextFrame.TextRange.Text = ""; continue; } if (s.Name == "txtCAJAS") { s.TextFrame.TextRange.Text = cantidadcajastemporal.ToString(); continue; } if (s.Name == "txtCONCATENADO1") { string GCAS = "", QUANTITY = ""; foreach (Campos c1 in ListaFinal) { if (c1.nombrecampo == "txtIRMSGCAS") { GCAS = c1.datocampo; } if (c1.nombrecampo == "txtQUANTITY") { QUANTITY = c1.datocampo; } } string verificar = etq.UnidadPesos, Unidades = ""; verificar = verificar.Substring(verificar.Length - 1); if (verificar == ".") { Unidades = etq.UnidadPesos.Remove(etq.UnidadPesos.Length - 1); } else { Unidades = etq.UnidadPesos; } string ConcatenadoTotal = "", ConcatenadoTotal2 = ""; ConcatenadoTotal = "91" + GCAS + "37" + QUANTITY + " " + Unidades; ConcatenadoTotal2 = "(91)" + GCAS + "(37)" + QUANTITY + " " + Unidades; s.TextFrame.TextRange.Text = ConcatenadoTotal2; string nombrecampo2 = s.Name.Replace("txt", "bcd"); campocodigo.nombrecodigo = nombrecampo2; campocodigo.datocodigo = ConcatenadoTotal; campocodigo.tipocodigo = 128; ListaCodigos.Add(campocodigo); } if (s.Name == "txtCONCATENADO2") { string LOT = "", PALLETTY = ""; foreach (Campos c1 in ListaFinal) { if (c1.nombrecampo == "txtLOT") { LOT = c1.datocampo; } if (c1.nombrecampo == "txtPALLETTYPE") { PALLETTY = c1.datocampo; } } string ConcatenadoTotal = "", ConcatenadoTotal2 = ""; ConcatenadoTotal = "10" + LOT + "90NONE"; ConcatenadoTotal2 = "(10)" + LOT + "(90)NONE"; s.TextFrame.TextRange.Text = ConcatenadoTotal2; string nombrecampo2 = s.Name.Replace("txt", "bcd"); campocodigo.nombrecodigo = nombrecampo2; campocodigo.datocodigo = ConcatenadoTotal; campocodigo.tipocodigo = 128; ListaCodigos.Add(campocodigo); } foreach (Campos c1 in ListaFinal) { if (s.Name == c1.nombrecampo) { if (diccionario_propiedadesEtq.Keys.Contains(c1.nombrecampo)) { if (diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.PesoNeto" || diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.PesoBruto" || diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.Tara") { s.TextFrame.TextRange.Text = c1.datocampo + " " + etq.UnidadPesos; bandera = true; break; } if (diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.ClaveProducto" && TipyVarEtqs.Key == 6 && TipyVarEtqs.Value == 1 && etq.Cliente.ToUpper().Contains("ORAL-B")) { if (c1.datocampo.Contains('-')) { if (c1.datocampo.Split('-').Length > 3) { s.TextFrame.TextRange.Text = "VARIOS"; bandera = true; break; } } else { s.TextFrame.TextRange.Text = c1.datocampo; bandera = true; break; } } else if (diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.Direccion") { string caadenadireccion = "", cadenaanterior = ""; if (c1.datocampo == null) { s.TextFrame.TextRange.Text = ""; } else { if (c1.datocampo.Contains("|")) { separadordireccion = c1.datocampo.Split(new string[] { "|" }, StringSplitOptions.None); foreach (string str in separadordireccion) { if (caadenadireccion == "") { cadenaanterior = str.Remove(0, 4); caadenadireccion = cadenaanterior; } else caadenadireccion = caadenadireccion + "\n" + str.Remove(0, 1); } } else { if (c1.datocampo == "") caadenadireccion = ""; else caadenadireccion = c1.datocampo.Remove(0, 4); } s.TextFrame.TextRange.Text = caadenadireccion; } bandera = true; break; } else { s.TextFrame.TextRange.Text = c1.datocampo; bandera = true; break; } } else { s.TextFrame.TextRange.Text = c1.datocampo; bandera = true; break; } } } if (bandera) continue; if (s.TextFrame.TextRange.Text.Contains("PALLET")) { if (cbx_PAQUETE.Checked) { if (etq.IdiomaETQ == 2) s.TextFrame.TextRange.Text = s.TextFrame.TextRange.Text.Replace("PALLET", "PACKAGE"); if (etq.IdiomaETQ == 1) s.TextFrame.TextRange.Text = s.TextFrame.TextRange.Text.Replace("PALLET", "PAQUETE"); } continue; } } } foreach (CamposCodigos cmp in ListaCodigosBaseDeDatos) { string nombrecampo = cmp.nombrecodigo.Replace("bcd", "txt"); foreach (Campos camps in ListaFinal) { if (camps.nombrecampo == nombrecampo) { CampoCodigo.nombrecodigo = cmp.nombrecodigo; CampoCodigo.datocodigo = camps.datocampo; CampoCodigo.tipocodigo = cmp.tipocodigo; ListaCodigos.Add(CampoCodigo); continue; } } } insertarCodigosDeBarraAWord(doc); if (File.Exists(@rutasEnModAdmin.RutaDeTemp + "/" + ContadorEtiquetas + "_0.pdf")) File.Delete((@rutasEnModAdmin.RutaDeTemp + "/" + ContadorEtiquetas + "_0.pdf")); doc.ExportAsFixedFormat(@rutasEnModAdmin.RutaDeTemp + "/" + ContadorEtiquetas + "_0.pdf", Word.WdExportFormat.wdExportFormatPDF, OptimizeFor: Word.WdExportOptimizeFor.wdExportOptimizeForPrint, BitmapMissingFonts: true, DocStructureTags: false); doc.SaveAs2(@rutasEnModAdmin.RutaDeTemp + "/docTemp.docx"); doc.Saved = true; ((Microsoft.Office.Interop.Word._Document)doc).Close(); ((Microsoft.Office.Interop.Word._Application)appWord).Quit(); File.Delete(@rutasEnModAdmin.RutaDeTemp + "/docTemp.docx"); File.Delete(@rutasEnModAdmin.RutaDeTemp + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx"); ContadorEtiquetas++; } } catch (Exception ex) { MessageBox.Show(ex.Message); this.matarProcesosWordExcel(); } }
public void datosaword(object sender, DoWorkEventArgs e) { try { matarProcesosWordExcel(); int ContadorEtiquetas = 1; foreach (KeyValuePair<int, int> TipyVarEtqs in Tipospalletfinal) { ListaCodigos = new List<CamposCodigos>(); CamposCodigos CampoCodigo; File.Copy(@rutasEnModAdmin.RutaDePlantillas + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx", @rutasEnModAdmin.RutaDeTemp + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx"); appWord = new Word.Application(); appWord.Visible = false; bool bandera = false; doc = appWord.Documents.Open(@rutasEnModAdmin.RutaDeTemp + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx"); foreach (Word.Shape s in doc.Shapes) { bandera = false; if (s.Type.ToString() == "msoTextBox") { s.Name = s.Name.Trim(); foreach (Campos c1 in ListaFinal) { if (s.Name == c1.nombrecampo) { if (diccionario_propiedadesEtq.Keys.Contains(c1.nombrecampo)) { if (diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.PesoNeto" || diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.PesoBruto" || diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.Tara") { s.TextFrame.TextRange.Text = c1.datocampo + " " + unidadeS; bandera = true; break; } else if (diccionario_propiedadesEtq[c1.nombrecampo] == "Etiqueta.Direccion") { string caadenadireccion = "", cadenaanterior = ""; if (c1.datocampo == null) { s.TextFrame.TextRange.Text = ""; } else { if (c1.datocampo.Contains("|")) { separadordireccion = c1.datocampo.Split(new string[] { "|" }, StringSplitOptions.None); foreach (string str in separadordireccion) { if (caadenadireccion == "") { cadenaanterior = str.Remove(0,4); caadenadireccion = cadenaanterior; } else caadenadireccion = caadenadireccion + "\n" + str.Remove(0,1); } } else { if (c1.datocampo == "") caadenadireccion = ""; else caadenadireccion = c1.datocampo.Remove(0,4); } s.TextFrame.TextRange.Text = caadenadireccion; } bandera = true; break; } else { if (s.Name == "txtPRODUCTCODE" || s.Name == "txtORDERNO") { if (c1.datocampo.Length > 29) s.TextFrame.TextRange.Font.Size = s.TextFrame.TextRange.Font.Size - 10; if (c1.datocampo.Length > 34) s.TextFrame.TextRange.Font.Size = s.TextFrame.TextRange.Font.Size - 10; if (c1.datocampo.Length > 41) s.TextFrame.TextRange.Font.Size = s.TextFrame.TextRange.Font.Size - 5; if (c1.datocampo.Length > 70) s.TextFrame.TextRange.Font.Size = s.TextFrame.TextRange.Font.Size - 5; } s.TextFrame.TextRange.Text = c1.datocampo; bandera = true; break; } } else { s.TextFrame.TextRange.Text = c1.datocampo; bandera = true; break; } } } if (bandera) continue; if (s.TextFrame.TextRange.Text.Contains("PALLET")) { if (cbx_PAQUETE.Checked) { if (etq.IdiomaETQ == 2) s.TextFrame.TextRange.Text = s.TextFrame.TextRange.Text.Replace("PALLET", "PACKAGE"); if (etq.IdiomaETQ == 1) s.TextFrame.TextRange.Text = s.TextFrame.TextRange.Text.Replace("PALLET", "PAQUETE"); } continue; } } } foreach (CamposCodigos cmp in ListaCodigosBaseDeDatos) { string nombrecampo = cmp.nombrecodigo.Replace("bcd", "txt"); foreach (Campos camps in ListaFinal) { if (camps.nombrecampo == nombrecampo) { CampoCodigo.nombrecodigo = cmp.nombrecodigo; CampoCodigo.datocodigo = camps.datocampo; CampoCodigo.tipocodigo = cmp.tipocodigo; ListaCodigos.Add(CampoCodigo); continue; } } } insertarCodigosDeBarraAWord(doc); if (File.Exists(@rutasEnModAdmin.RutaDeTemp + "/" + ContadorEtiquetas + "_0.pdf")) File.Delete((@rutasEnModAdmin.RutaDeTemp + "/" + ContadorEtiquetas + "_0.pdf")); doc.ExportAsFixedFormat(@rutasEnModAdmin.RutaDeTemp + "/" + ContadorEtiquetas + "_0.pdf", Word.WdExportFormat.wdExportFormatPDF, OptimizeFor: Word.WdExportOptimizeFor.wdExportOptimizeForPrint, BitmapMissingFonts: true, DocStructureTags: false); doc.SaveAs2(@rutasEnModAdmin.RutaDeTemp + "/docTemp.docx"); doc.Saved = true; ((Microsoft.Office.Interop.Word._Document)doc).Close(); ((Microsoft.Office.Interop.Word._Application)appWord).Quit(); File.Delete(@rutasEnModAdmin.RutaDeTemp + "/docTemp.docx"); File.Delete(@rutasEnModAdmin.RutaDeTemp + "/Etq_" + TipyVarEtqs.Key.ToString() + "_" + TipyVarEtqs.Value.ToString() + ".docx"); ContadorEtiquetas++; //} } } catch (Exception ex) { MessageBox.Show(ex.Message); this.matarProcesosWordExcel(); } }
private void _Search(List<string> pathToFile, string stringToSearch, string pathToSave = null) { logger.Info("Clean the return List of coincidences"); FileInfo.Clear(); logger.Info("initializing paramenter objects"); object oMissing = System.Reflection.Missing.Value; object oTrue = true; object oFalse = false; try { logger.Info("instantiating word app"); word = new Word.Application(); logger.Info("instantiating document of word app"); doc = new Word.Document(); logger.Info("reading each files on path ={0}", pathToFile); foreach (string item in pathToFile) { object fileName = item; logger.Info("opening the file"); doc = word.Documents.Open(ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oFalse, ref oMissing, ref oMissing, ref oMissing, ref oMissing); doc.Activate(); logger.Info("file opened and activates"); FileInfo fiIn = new FileInfo(); fiIn.FileName = item; fiIn.FileNameOut = string.Format(@"{0}\{1}.pdf", pathToSave, Guid.NewGuid().ToString()); logger.Info("searching the text on each paragraphs"); foreach (Word.Paragraph Paragraph in doc.Paragraphs) { Word.Range rng = Paragraph.Range; rng.Find.Text = stringToSearch.Trim(); rng.Find.ClearFormatting(); rng.Find.Forward = true; rng.Find.Replacement.ClearFormatting(); rng.Find.Wrap = Word.WdFindWrap.wdFindStop; rng.Find.Execute( ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); while (rng.Find.Found) { rng.HighlightColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkYellow; rng.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdWhite; MatchesInfo maIn = new MatchesInfo(); maIn.Page = (int)rng.get_Information(Microsoft.Office.Interop.Word.WdInformation.wdActiveEndAdjustedPageNumber); maIn.Line = (int)rng.get_Information(Microsoft.Office.Interop.Word.WdInformation.wdFirstCharacterLineNumber); fiIn.MatchesList.Add(maIn); logger.Info("text matching and highlight"); rng.Find.Execute( ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); } } FileInfo.Add(fiIn); if (!string.IsNullOrEmpty(pathToSave)) { logger.Info("exporting the file"); doc.ExportAsFixedFormat( fiIn.FileNameOut, Word.WdExportFormat.wdExportFormatPDF, OptimizeFor: Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, BitmapMissingFonts: true, DocStructureTags: false); logger.Info("file exported"); } object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; object originalFormat = Word.WdOriginalFormat.wdOriginalDocumentFormat; object routeDocument = false; ((Word._Document)doc).Close(ref saveOption, ref originalFormat, ref routeDocument); } } catch (Exception ex) { //TODO: Manipular errores; logger.Info("An exception has detected"); logger.Error(ex); throw new Exception(""); throw; } finally { ((Word._Application)word).Quit(ref oFalse, ref oMissing, ref oMissing); } }