/// <summary> /// Generate a Picture instance, which can be inserted into a Document /// </summary> /// <param name="scalar">The scaling factor (0.5 is 50%)</param> public Picture Picture(double scalar) { if (!Loaded) { throw new InvalidDataException("Templ: Tried to generate a Picture from a Graphic before the Graphic was loaded into a Document"); } var pic = Image.CreatePicture(); pic.Width = (int)(pic.Width * (scalar)); pic.Height = (int)(pic.Height * (scalar)); return(pic); }
//added by LIUJIE 2017-09-18 /// <summary> /// 插入图片及图片注释(对图片尺寸没有要求) /// </summary> /// <param name="oldPath">添加的doc路径</param> /// <param name="oPath">添加图片的数组</param> /// <param name="replaceFlag">替换符</param> /// <param name="oRemark">图片备注数组</param> public void AddWordPic(string oldPath, object[] oPath, string replaceFlag, object[] oRemark) { DocX oldDocument = DocX.Load(oldPath); Paragraph ss = null; Novacode.Image img = null; ss = GetParagraphByReplaceFlag(oldDocument, replaceFlag, "CENTER"); ss.ReplaceText(replaceFlag, ""); if (!(oPath == null || oRemark == null)) { try { string[] imagePath = classLims_NPOI.dArray2String1(oPath); string[] remark = classLims_NPOI.dArray2String1(oRemark); for (int i = 0; i < imagePath.Length; i++) { img = oldDocument.AddImage(imagePath[i]); Picture pic = img.CreatePicture(); ss.AppendPicture(pic); pic.Height = Convert.ToInt32(Convert.ToDouble(pic.Height) / Convert.ToDouble(pic.Width) * Convert.ToDouble(oldDocument.PageWidth)); pic.Width = Convert.ToInt32(Convert.ToDouble(oldDocument.PageWidth)); ss.AppendLine(remark[i] + "\n"); //ss.AppendLine("\n"); ss.Alignment = Alignment.center; } } catch (System.InvalidOperationException e) { classLims_NPOI.WriteLog(e, ""); return; } } oldDocument.Save(); return; }
//插入图片,插入的位置可以调整的,不过这里没写 public static void addPicture(string docx, string imgpath) { // Create a document using a relative filename. using (DocX document = DocX.Load(docx)) { // Add an Image to this document.但是并没有把图片插入到文档里 //插入到文档的得是由image创建的pic // 设置旋转度数 //pic.Rotation = 10; // 设置大小. //pic.Width = 400; //pic.Height = 300; // 设置形状. //pic.SetPictureShape(BasicShapes.cube);//cube 立方体 //不设置shape就是默认的矩形 // Flip the Picture Horizontally. // pic.FlipHorizontal = true; Image img1 = document.AddImage(imgpath); Picture pic1 = img1.CreatePicture(); document.InsertParagraph().AppendPicture(pic1); document.Save(); }// Release this document from memory. }
private void InsertScreenshot() { Process.Start(binaryPath); Thread.Sleep(1000); string[] binaryPathSplit = binaryPath.Split('\\'); Process[] process = Process.GetProcessesByName(binaryPathSplit[binaryPathSplit.Length - 1].Remove(binaryPathSplit[binaryPathSplit.Length - 1].Length - 4)); var rectangle = new User32.Rect(); User32.GetWindowRect(process[0].MainWindowHandle, ref rectangle); int width = rectangle.right - rectangle.left; int height = rectangle.bottom - rectangle.top; screenshot = new Bitmap(width - 18, height - 9, PixelFormat.Format32bppRgb); // TODO Graphics graphics = Graphics.FromImage(screenshot); graphics.CopyFromScreen(rectangle.left + 9, rectangle.top, 0, 0, new Size(width - 9, height - 9), CopyPixelOperation.SourceCopy); screenshot.Save("image.png", ImageFormat.Bmp); process[0].Kill(); Novacode.Image image = document.AddImage("image.png"); paragraphCodePicture = document.InsertParagraph("", false); Picture picture = image.CreatePicture(); paragraphCodePicture.InsertPicture(picture); //File.Delete("image.png"); // DEBUG }
private void insertarGraficoBarra(DocX doc, Empresa empresa, string strDirectorio) { var RVFormat = new Novacode.Formatting(); RVFormat.FontFamily = new System.Drawing.FontFamily("Calibri"); RVFormat.Size = 12D; RVFormat.Bold = true; Paragraph pTit = doc.InsertParagraph("Recursos Valiosos " + empresa.NombreEmpresa.ToUpper(), false, RVFormat); pTit.Alignment = Alignment.left; var RVParrafo = new Novacode.Formatting(); RVParrafo.FontFamily = new System.Drawing.FontFamily("Calibri"); RVParrafo.Size = 12D; RVParrafo.Position = 3; Paragraph pParr = doc.InsertParagraph("Se definen los recursos físicos, organizacionales e intangibles con los que cuenta " + empresa.NombreEmpresa.ToUpper() + ". Los recursos definidos son evaluados por parte del equipo técnico – gerencial desde la perspectiva de inimitable, durabilidad, apropiación, sustitución y superioridad competitiva.", false, RVParrafo); pParr.Alignment = Alignment.left; string strGrafico = CrearGraficoBarra(empresa, strDirectorio); Novacode.Image i = doc.AddImage(strGrafico); Picture p = i.CreatePicture(); Paragraph pImg = doc.InsertParagraph("").AppendPicture(p); pImg.Alignment = Alignment.center; }
/// <summary> /// Method that creates a Microsoft Word Document full of the QR code images that are associated with each question /// of the current treasure hunt and passes to the Print view the location of where this new file is stored. /// </summary> public void ExecutePrintQRCodesCommand() { PopupMessage = "Preparing..."; PopupDisplayed = true; NewQuestion = null; //-http://cathalscorner.blogspot.co.uk/2009/04/docx-version-1002-released.html //The location of where this word document will be stored. String newDocumentFileLocation = myFileDirectory + "Documents\\" + this.currentTreasureHunt.HuntName + " QR Codes Sheet.docx"; //The creation of this new Word Document for the file location supplied using (DocX documentOfQRCodes = DocX.Create(newDocumentFileLocation)) { Novacode.Paragraph p = documentOfQRCodes.InsertParagraph(this.currentTreasureHunt.HuntName); documentOfQRCodes.InsertParagraph(); //For every question associated with the current treasure hunt using (var currentQuestionQRCode = this.questions.GetEnumerator()) { while (currentQuestionQRCode.MoveNext()) { if (currentQuestionQRCode.Current.URL != null && currentQuestionQRCode.Current.URL != "empty URL") { //Insert into the document the QR associated with the current question documentOfQRCodes.InsertParagraph(currentQuestionQRCode.Current.Question1); documentOfQRCodes.InsertParagraph(); Novacode.Paragraph q = documentOfQRCodes.InsertParagraph(); string locationOfImage = myFileDirectory + "QRCodes\\" + CurrentTreasureHunt.HuntId + " " + currentQuestionQRCode.Current.Question1 + ".png"; Novacode.Image img = documentOfQRCodes.AddImage(@locationOfImage); Picture pic1 = img.CreatePicture(); q.InsertPicture(pic1, 0); pic1.Width = 200; pic1.Height = 200; documentOfQRCodes.InsertParagraph(); } } } documentOfQRCodes.Save(); PopupDisplayed = false; } Messenger.Default.Send <UpdateViewMessage>(new UpdateViewMessage() { UpdateViewTo = "PrintViewModel" }); Messenger.Default.Send <PrintMessage>(new PrintMessage() { FileLocation = newDocumentFileLocation }); Messenger.Default.Send <SelectedHuntMessage>(new SelectedHuntMessage() { CurrentHunt = this.currentTreasureHunt }); }
/// <summary> /// 插入图片(对图片尺寸没有要求) /// </summary> /// <param name="doc"></param> /// <param name="replaceFlag"></param> /// <param name="imgPath"></param> /// <param name="alignment">对齐方式</param> public Picture InsertPicture(DocX doc, string replaceFlag, string imgPath, string alignment) { Paragraph p = GetParagraphByReplaceFlag(doc, replaceFlag, alignment); if (p == null) { return(null); } p.ReplaceText(replaceFlag, ""); Novacode.Image img = null; try { img = doc.AddImage(imgPath); } catch (System.InvalidOperationException e) { classLims_NPOI.WriteLog(e, ""); return(null); } Novacode.Picture pic = img.CreatePicture(); //p.AppendPicture(pic); p.InsertPicture(pic); pic.Height = Convert.ToInt32(Convert.ToDouble(pic.Height) / Convert.ToDouble(pic.Width) * Convert.ToDouble(doc.PageWidth - doc.MarginLeft - doc.MarginRight)); pic.Width = Convert.ToInt32(Convert.ToDouble(doc.PageWidth - doc.MarginLeft - doc.MarginRight)); return(pic); }
/// <summary> /// Creates a Novacode Picture from a local image file such as .PNP, .JPG etc /// </summary> /// <param name="document">Referce to the global document</param> /// <param name="Directory">File directory of the local image file</param> /// <param name="Height">Height of the picture</param> /// <param name="Width">Width of the picture</param> /// <returns>Returns a picture of type Novacode.Picture</returns> public Picture CreatePicture(ref DocX document, string Directory, int Height, int Width) { Novacode.Image image = document.AddImage(Directory); // Create a picture (A custom view of an Image). Picture picture = image.CreatePicture(); picture.Height = Height; picture.Width = Width; return(picture); }
public DocX AddImg(string ImagePath) { Novacode.Image img = this.Document.AddImage(ImagePath); Picture pic = img.CreatePicture(); pic.Height = 250; pic.Width = 600; this.document.InsertParagraph().Alignment = Alignment.center; this.document.InsertParagraph().InsertPicture(pic); return(this.Document); }
public void AddImage(string link, int width, int height) { Novacode.Image image = this.document.AddImage(link); Picture picture = image.CreatePicture(); picture.Width = width; picture.Height = height; Paragraph p1 = this.document.InsertParagraph(); p1.AppendPicture(picture); }
//make internal public void ExecutePrintQRCodesCommand() { NewQuestion = null; //-http://cathalscorner.blogspot.co.uk/2009/04/docx-version-1002-released.html String newDocumentFileLocation = myFileDirectory + "Documents\\" + this.currentTreasureHunt.HuntName + " QR Codes Sheet.docx"; //if(File.Exists(myFileDirectory + "Documents\\" + this.currentTreasureHunt.HuntName + " QR Codes Sheet.docx") //{ using (DocX documentOfQRCodes = DocX.Create(newDocumentFileLocation)) { Novacode.Paragraph p = documentOfQRCodes.InsertParagraph(this.currentTreasureHunt.HuntName); Novacode.Paragraph space = documentOfQRCodes.InsertParagraph(""); documentOfQRCodes.InsertParagraph(); using (var currentQuestionQRCode = this.questions.GetEnumerator()) { while (currentQuestionQRCode.MoveNext()) { if (currentQuestionQRCode.Current.URL != null && currentQuestionQRCode.Current.URL != "empty URL") { documentOfQRCodes.InsertParagraph(currentQuestionQRCode.Current.Question1); Novacode.Paragraph q = documentOfQRCodes.InsertParagraph(); string locationOfImage = myFileDirectory + "QRCodes\\" + CurrentTreasureHunt.HuntId + " " + currentQuestionQRCode.Current.Question1 + ".png"; Novacode.Image img = documentOfQRCodes.AddImage(@locationOfImage); Picture pic1 = img.CreatePicture(); q.InsertPicture(pic1, 0); pic1.Width = 200; pic1.Height = 200; documentOfQRCodes.InsertParagraph(); } } } documentOfQRCodes.Save(); } Messenger.Default.Send <UpdateViewMessage>(new UpdateViewMessage() { UpdateViewTo = "PrintViewModel" }); Messenger.Default.Send <PrintMessage>(new PrintMessage() { FileLocation = newDocumentFileLocation }); Messenger.Default.Send <SelectedHuntMessage>(new SelectedHuntMessage() { CurrentHunt = this.currentTreasureHunt }); }
public MemoryStream ExportDocxFile(List <string> imgDatas) { using (var document = DocX.Load($@"{_hostingEnvironment.WebRootPath}/ChartTest.docx")) { var imageTableIdx = 1;//定義第一張圖的表格位置 var ImageTableIndex = new List <int>() { 1, 3, 5, 7, 8, 9 }; var failImage = new List <int>(); using (var ms = new MemoryStream()) { var mmsg = ""; var imageTable = document.Tables[0];// foreach (var imgData in imgDatas) { using (var Img = GenerateHighChartImage(imgData, ref mmsg)) { if (Img != null) { Img.Save(ms, ImageFormat.Png);//Save your picture in a memory stream. ms.Seek(0, SeekOrigin.Begin); Novacode.Image img = document.AddImage(ms); //Paragraph p = document.InsertParagraph("Hello", false); Picture pic1 = img.CreatePicture(); var row = imageTable.Rows[0]; row.MergeCells(0, 1); var MaxWidth = row.Cells[0].Width; var ratio = MaxWidth / Img.Width; var width = Math.Round((double)Img.Width * 0.35); var height = Math.Round((double)Img.Height * 0.35); row.Cells[0].Paragraphs[0].Alignment = Alignment.center; row.Cells[0].Paragraphs[0].InsertPicture(pic1, 0); row.Cells[0].VerticalAlignment = VerticalAlignment.Center; // imageTable.Alignment = Alignment.center; //imageTableIdx += 2; } } } } var memory = new MemoryStream(); document.SaveAs(memory); return(memory); //return FileTool.ConvertDocToMemoryStream(document); } }
// Create an invoice for a factitious company called "The Happy Builder". private static DocX CreateInvoiceFromTemplate(DocX template) { #region Logo // A quick glance at the template shows us that the logo Paragraph is in row zero cell 1. Paragraph logo_paragraph = template.Tables[0].Rows[0].Cells[1].Paragraphs[0]; // Remove the template Picture that is in this Paragraph. logo_paragraph.Pictures[0].Remove(); // Add the Happy Builders logo to this document. Novacode.Image logo = template.AddImage(@"images\logo_the_happy_builder.png"); // Insert the Happy Builders logo into this Paragraph. logo_paragraph.InsertPicture(logo.CreatePicture()); #endregion #region Set CustomProperty values // Set the value of the custom property 'company_name'. template.AddCustomProperty(new CustomProperty("company_name", "The Happy Builder")); // Set the value of the custom property 'company_slogan'. template.AddCustomProperty(new CustomProperty("company_slogan", "No job too small")); // Set the value of the custom properties 'hired_company_address_line_one', 'hired_company_address_line_two' and 'hired_company_address_line_three'. template.AddCustomProperty(new CustomProperty("hired_company_address_line_one", "The Crooked House,")); template.AddCustomProperty(new CustomProperty("hired_company_address_line_two", "Dublin,")); template.AddCustomProperty(new CustomProperty("hired_company_address_line_three", "12345")); // Set the value of the custom property 'invoice_date'. template.AddCustomProperty(new CustomProperty("invoice_date", DateTime.Today.Date.ToString("d"))); // Set the value of the custom property 'invoice_number'. template.AddCustomProperty(new CustomProperty("invoice_number", 1)); // Set the value of the custom property 'hired_company_details_line_one' and 'hired_company_details_line_two'. template.AddCustomProperty(new CustomProperty("hired_company_details_line_one", "Business Street, Dublin, 12345")); template.AddCustomProperty(new CustomProperty("hired_company_details_line_two", "Phone: 012-345-6789, Fax: 012-345-6789, e-mail: [email protected]")); #endregion /* * InvoiceTemplate.docx contains a blank Table, * we want to replace this with a new Table that * contains all of our invoice data. */ Table t = template.Tables[1]; Table invoice_table = CreateAndInsertInvoiceTableAfter(t, ref template); t.Remove(); // Return the template now that it has been modified to hold all of our custom data. return(template); }
/// <summary> /// 替换图片标签(使用DocX.dll类库,调用这个方法后NPOI无法读取文档) /// </summary> /// <param name="strDataSourcePath">Word文件路径</param> /// <param name="strLabelName">标签名称(带标签符号)</param> /// <param name="strImagePath">替换的图片路径</param> /// <param name="iImageWidth">替换的图片宽度(小于0则显示原图宽度)</param> /// <param name="iImageHeight">替换的图片高度(小于0则显示原图高度)</param> /// <returns>成功返回替换数量,失败返回-1</returns> public static int ReplaceImageLabel(string strDataSourcePath, string strLabelName, string strImagePath, int iImageWidth, int iImageHeight) { try { if (string.IsNullOrEmpty(strDataSourcePath) || !File.Exists(strDataSourcePath) || string.IsNullOrEmpty(strLabelName) || string.IsNullOrEmpty(strImagePath) || !File.Exists(strImagePath)) { return(-1); } int iNumber = 0; //使用DocX.dll类库 DocX mDocX = DocX.Load(strDataSourcePath); //遍历段落 foreach (Paragraph wordParagraph in mDocX.Paragraphs) { if (wordParagraph.Text.IndexOf(strLabelName) >= 0) { //添加图片 Novacode.Image pImag = mDocX.AddImage(strImagePath); Picture pPicture = pImag.CreatePicture(); //如果传入宽度小于0,则以原始大小插入 if (iImageWidth >= 0) { pPicture.Width = iImageWidth; } //如果传入高度小于0,则以原始大小插入 if (iImageHeight >= 0) { pPicture.Height = iImageHeight; } //将图像插入到段落后面 wordParagraph.InsertPicture(pPicture); //清空文本(清空放在前面会导致替换失败文字消失) wordParagraph.ReplaceText(strLabelName, string.Empty); iNumber++; } } mDocX.SaveAs(strDataSourcePath); return(iNumber); } catch (Exception ex) { TXTHelper.Logs(ex.ToString()); return(-1); } }
private bool AddGraphImageToDoc(string fileName, Bitmap bmp) { using (MemoryStream ms = new MemoryStream()) { bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); ms.Seek(0, SeekOrigin.Begin); try { if (System.IO.File.Exists(fileName)) { using (DocX doc = DocX.Load(fileName)) { Novacode.Image img = doc.AddImage(ms); Paragraph p = doc.InsertParagraph(); p.Alignment = Alignment.center; p.Append("\n"); Picture pic1 = img.CreatePicture(); p.InsertPicture(pic1, 0); doc.Save(); } } else { using (DocX doc = DocX.Create(fileName)) { Novacode.Image img = doc.AddImage(ms); // Create image. Paragraph p = doc.InsertParagraph(); p.Alignment = Alignment.center; p.Append("\n"); Picture pic1 = img.CreatePicture(); p.InsertPicture(pic1, 0); doc.Save(); } } } catch (Exception e) { return(false); } return(true); } }
/// <summary> /// Creates a Novacode Picture from a Bitmap /// </summary> /// <param name="document">Referce to the document</param> /// <param name="bmp">Bitmap to be converted</param> /// <param name="Height">Height of the picture</param> /// <param name="Width">Width of the picture</param> /// <returns>Returns a picture of type Novacode.Picture</returns> public Picture CreatePicture(ref DocX document, Bitmap bmp, int Height, int Width) { System.Drawing.Image image = (System.Drawing.Image)bmp; using (MemoryStream ms = new MemoryStream()) { image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);// Save your picture in a memory stream. //image.Save(ms, bmp.RawFormat); ms.Seek(0, SeekOrigin.Begin); Novacode.Image NovaImage = document.AddImage(ms); // Create image. Picture picture = NovaImage.CreatePicture(); // Create picture. picture.Height = Height; picture.Width = Width; return(picture); } }
//替换图片,使用原始尺寸 /// <summary> /// 替换图片,使用原始尺寸 /// </summary> /// <param name="doc"></param> /// <param name="parIndex">有图片的段落的索引</param> /// <param name="imgPath">图片路径</param> /// <param name="alignment">对齐方式</param> /// <returns></returns> private Picture replacePicture(DocX doc, int parIndex, string imgPath, string alignment) { List <Paragraph> listPar = getPictureParagraphs(doc); if (listPar == null) { return(null); } if (listPar.Count < parIndex) { return(null); } if (getParagraphPictures(listPar[parIndex], 0) == null) { return(null); } Novacode.Image img = null; try { img = doc.AddImage(imgPath); } catch (System.InvalidOperationException e) { classLims_NPOI.WriteLog(e, ""); return(null); } Picture pic = img.CreatePicture(); Paragraph par = listPar[parIndex]; par.Pictures[0].Remove(); //par.Pictures.Add(pic); par.InsertPicture(pic); pic.Height = Convert.ToInt32(Convert.ToDouble(pic.Height) / Convert.ToDouble(pic.Width) * Convert.ToDouble(doc.PageWidth - doc.MarginLeft - doc.MarginRight)); pic.Width = Convert.ToInt32(Convert.ToDouble(doc.PageWidth - doc.MarginLeft - doc.MarginRight)); return(pic); }
//public static bool AddHyperLink(string linkText, string href, string fileName = null, string ouputFolderPath = null, string outputFolderName = null) //{ // IDictionary<string, string> file = ReturnFileMembers(fileName, ouputFolderPath, outputFolderName); // if (string.IsNullOrWhiteSpace(file["name"]) || !File.Exists(file["fullPath"])) // return false; // using (var document = DocX.Load(file["fullPath"])) // { // document.AddHyperlink(linkText, new Uri(href));//this doesn't seem to work // document.Save(); // } // return true; //} public static bool AddImage(string imgName, string fileName = null, string ouputFolderPath = null, string outputFolderName = null) { var imgPath = Path.Combine(DefaultResourcesFolderPath, DefaultResourcesFolderName, imgName + "." + ImageFileExtension); IDictionary <string, string> file = ReturnFileMembers(fileName, ouputFolderPath, outputFolderName); if (string.IsNullOrWhiteSpace(file["name"]) || !File.Exists(file["fullPath"]) || !File.Exists(imgPath)) { return(false); } using (var document = DocX.Load(file["fullPath"])) { using (MemoryStream ms = new MemoryStream()) { System.Drawing.Image myImg = System.Drawing.Image.FromFile(imgPath); myImg.Save(ms, myImg.RawFormat); // Save your picture in a memory stream. ms.Seek(0, SeekOrigin.Begin); Novacode.Image img = document.AddImage(ms); // Create image. var paragraphFormat = new Formatting(); paragraphFormat.Position = 5; Paragraph p = document.InsertParagraph("", false, paragraphFormat); Picture pic1 = img.CreatePicture(); // Create picture. var picDimensions = ReturnPicDimensions(document, pic1); pic1.Width = picDimensions[0]; pic1.Height = picDimensions[1]; p.InsertPicture(pic1, 0); // Insert picture into paragraph. p.Alignment = Alignment.center; document.Save(); } } return(true); }
{ /// <summary> /// create doc or docx /// using DOCX: Novacode /// </summary> public static void CreateDocStreamBySvgs(List <SvgDocument> svgDocs, Stream stream) { using (stream) { using (DocX doc = DocX.Create(stream)) { Novacode.Paragraph p = doc.InsertParagraph("", false); for (int i = 0; i < svgDocs.Count; i++) { using (MemoryStream ms = new MemoryStream()) { System.Drawing.Bitmap image = svgDocs[i].Draw(); image.Save(ms, ImageFormat.Bmp); ms.Seek(0, SeekOrigin.Begin); Novacode.Image img = doc.AddImage(ms); Novacode.Picture pic = img.CreatePicture(); p.AppendPicture(pic); } } doc.Save(); } } }
public void InsertPictureToCell(Table dt, int rowIndex, int cellIndex, int width, int height, string url) { var p = dt.Rows[rowIndex].Cells[cellIndex].Paragraphs[0]; using (var ms = new MemoryStream()) { var request = WebRequest.Create(url); var response = request.GetResponse(); var stream = response.GetResponseStream(); const int bufferLength = 1024; int actual; byte[] buffer = new byte[bufferLength]; while ((actual = stream.Read(buffer, 0, bufferLength)) > 0) { ms.Write(buffer, 0, actual); } ms.Position = 0; Novacode.Image img = _document.AddImage(ms); var pic = img.CreatePicture(width, height); p.InsertPicture(pic); p.Alignment = Alignment.center; } }
/// <summary> /// Doc中插入图片 /// </summary> /// <param name="keyWord">doc模板中的关键字 用于替换</param> /// <param name="imagePath">图片路径 绝对路径 Server.MapPath()</param> /// <param name="width">100</param> /// <param name="height">100</param> public void InsertImage(string keyWord, string imagePath, int width, int height) { var Paragraphs = this.document.Paragraphs; //给文档添加1个图像 Novacode.Image img = document.AddImage(imagePath); //将图像插入到段落后面 Picture pic = img.CreatePicture(height, width); //设置图片形状,并水平翻转图片 pic.SetPictureShape(RectangleShapes.rect); //(BasicShapes.cube); pic.FlipHorizontal = false; //不反轉 List <Novacode.Paragraph> removes = new List <Novacode.Paragraph>(); foreach (Novacode.Paragraph p in Paragraphs) { List <int> indexes = p.FindAll(keyWord); if (indexes.Count > 0) { p.InsertPicture(pic, 0); p.ReplaceText(keyWord, ""); } } }
private static Paragraph AddPicture(Topic topic, string pictureName, DocX doc, Paragraph p) { if (topic.Snapshots == null) { return(p); } List <KeyValuePair <string, byte[]> > snapshots = topic.Snapshots.Where(item => item.Key.Contains(pictureName)).ToList(); if (snapshots.Count == 0) { return(p); } System.IO.MemoryStream myMemStream = Services.BCFServices.GetImageStreamFromBytes(snapshots.FirstOrDefault().Value, false); //System.Drawing.Image fullsizeImage = System.Drawing.Image.FromStream(myMemStream); // Add an Image to the docx file Novacode.Image img = doc.AddImage(myMemStream); //myMemStream.Close(); Novacode.Picture pic = img.CreatePicture(); //Create a image with more or less the width of the page int newWidth = 568; double ratio = Convert.ToDouble(pic.Height) / Convert.ToDouble(pic.Width); int newHeight = Convert.ToInt16(Math.Round(ratio * newWidth)); pic.Height = newHeight; pic.Width = newWidth; p = doc.InsertParagraph(""); p = doc.InsertParagraph(""); p.InsertPicture(pic); return(p); }
private void insertarGraficosTortas(DocX doc, Empresa empresa, string strDirectorio) { List <RBV_Clases.RecursoValioso> recursosValiosos = new List <RBV_Clases.RecursoValioso>(); List <Entidades.MatrizValoracion> MatrizValoracion = new List <RBV_Clases.MatrizValoracion>(); decimal ValorTotal = 0; MatrizValoracion = RBV_Negocio.MatrizBO.ConsultarMatrizValoracion(empresa.IdEmpresa).OrderBy(p => p.IdCaracteristica).ThenBy(p => p.IdRecurso).ToList(); if (MatrizValoracion.Count > 0) { recursosValiosos = RBV_Negocio.MatrizBO.CalcularResultadosMatriz(MatrizValoracion, empresa.IdEmpresa); ValorTotal = recursosValiosos.Sum(p => p.Valor) / recursosValiosos.Count; } var RVFormat = new Novacode.Formatting(); RVFormat.FontFamily = new System.Drawing.FontFamily("Calibri"); RVFormat.Size = 12D; RVFormat.Bold = true; var RVParrafo = new Novacode.Formatting(); RVParrafo.FontFamily = new System.Drawing.FontFamily("Calibri"); RVParrafo.Size = 12D; RVParrafo.Position = 3; string strGraficoTortaRecursos = CrearTortaRecursos(empresa, strDirectorio, recursosValiosos); string strGraficoTortaRecursosSobreTotal = CrearTortaRecursosSobreTotal(empresa, strDirectorio, recursosValiosos, ValorTotal); string strGraficoTortaRecursosSobreValiosos = CrearTortaRecursosValiososSobreValiosos(empresa, strDirectorio, recursosValiosos, ValorTotal); string strGraficoBarrasHorinzotales = CrearGraficoBarrasHorizontalesClasificacion(empresa, strDirectorio, MatrizValoracion, ValorTotal); //Torta de porcentajes Paragraph pTit = doc.InsertParagraph("Porcentajes de Recursos", false, RVFormat); pTit.Alignment = Alignment.left; Paragraph pParr = doc.InsertParagraph("Aquí va el análisis a la torta de porcentaje ", false, RVParrafo); pParr.Alignment = Alignment.left; Novacode.Image i = doc.AddImage(strGraficoTortaRecursos); Picture pic = i.CreatePicture(); Paragraph pImg = doc.InsertParagraph("").AppendPicture(pic); pImg.Alignment = Alignment.center; //Torta de porcentajes sobre recursos total pTit = doc.InsertParagraph("Porcentajes de Recursos valiosos sobre el total de los recursos", false, RVFormat); pTit.Alignment = Alignment.left; pParr = doc.InsertParagraph("Aquí va el análisis a la torta de porcentaje ", false, RVParrafo); pParr.Alignment = Alignment.left; i = doc.AddImage(strGraficoTortaRecursosSobreTotal); pic = i.CreatePicture(); pImg = doc.InsertParagraph("").AppendPicture(pic); pImg.Alignment = Alignment.center; //Torta de porcentajes sobre valiosos pTit = doc.InsertParagraph("Porcentajes de Recursos valiosos sobre el total de los valiosos", false, RVFormat); pTit.Alignment = Alignment.left; pParr = doc.InsertParagraph("Aquí va el análisis a la torta de porcentaje", false, RVParrafo); pParr.Alignment = Alignment.left; i = doc.AddImage(strGraficoTortaRecursosSobreValiosos); pic = i.CreatePicture(); pImg = doc.InsertParagraph("").AppendPicture(pic); pImg.Alignment = Alignment.center; //Torta de barras horizonteles pTit = doc.InsertParagraph("Recursos contra clasificación", false, RVFormat); pTit.Alignment = Alignment.left; pParr = doc.InsertParagraph("Aquí va el análisis de barras horizontales", false, RVParrafo); pParr.Alignment = Alignment.left; i = doc.AddImage(strGraficoBarrasHorinzotales); pic = i.CreatePicture(); pImg = doc.InsertParagraph("").AppendPicture(pic); pImg.Alignment = Alignment.center; }
public static void createTaskDocument(List <string> textForQRcode, string nameWorker, List <string> typeOfWork, List <string> infoAboutAuto, List <string> infoAboutDetails, List <DateTime> dateTimeStart, List <DateTime> dateTimeFinish) { // Create a document in memory: var doc = DocX.Create("Task" + ".docx"); doc.PageLayout.Orientation = Novacode.Orientation.Landscape; for (int i = 0; i < textForQRcode.Count(); i++) { var text = "Завдання \"" + typeOfWork[i] + "\"\n\n"; var format = new Formatting(); format.Size = 24D; format.FontFamily = new System.Drawing.FontFamily("Times New Roman"); var format1 = new Formatting(); format1.Size = 20D; format1.Bold = true; format1.FontFamily = new System.Drawing.FontFamily("Times New Roman"); Paragraph title = doc.InsertParagraph(text, false, format); title.Alignment = Alignment.center; Novacode.Table table = doc.AddTable(1, 3); table.Design = Novacode.TableDesign.TableNormal; table.Alignment = Alignment.left; using (var ms = new MemoryStream()) { System.Drawing.Image qrCode = generateQR(textForQRcode[i]); qrCode.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); // Save your picture in a memory stream. ms.Seek(0, SeekOrigin.Begin); Novacode.Image img = doc.AddImage(ms); // Create image. Picture pic1 = img.CreatePicture(); // Create picture. table.Rows[0].Cells[0].Paragraphs.First().InsertPicture(pic1, 0); } format.Size = 18D; table.SetWidths(new float[] { 300, 200, 750 }); table.Rows[0].Cells[2].Paragraphs.First().InsertText("Автомобіль - ", false, format); table.Rows[0].Cells[2].Paragraphs.First().InsertText(infoAboutAuto[i], false, format1); table.Rows[0].Cells[2].InsertParagraph("Деталі : \n", false, format).InsertText(infoAboutDetails[i], false, format1); table.Rows[0].Cells[2].InsertParagraph("Виконавець(по плану) - ", false, format).InsertText(nameWorker, false, format1); table.Rows[0].Cells[2].InsertParagraph("Початок роботи - ", false, format).InsertText(dateTimeStart[i].ToString(), false, format1); table.Rows[0].Cells[2].InsertParagraph("Кінець роботи - ", false, format).InsertText(dateTimeFinish[i].ToString(), false, format1); doc.InsertTable(table); if (textForQRcode.Count() - i > 1) { doc.InsertSectionPageBreak(); } doc.PageLayout.Orientation = Novacode.Orientation.Landscape; } doc.Save(); ViewModels.ClassForAudio.playScan(); }
public override object Template(Int32 CompanyId, string templateBlobPath, Dictionary <string, string> templateKeywords) { util.ContainerName = "company-" + CompanyId; string blobName = util.getBlob(templateBlobPath); _cblob = util.BlobContainer.GetBlockBlobReference(blobName); //_cblob.FetchAttributes(); var ms = new MemoryStream(); _cblob.DownloadToStream(ms); long fileByteLength = _cblob.Properties.Length; byte[] fileContents = new byte[fileByteLength]; _cblob.DownloadToByteArray(fileContents, 0); DocX _template = DocX.Load(ms); if (templateKeywords != null && templateKeywords.Keys.Count > 0) { foreach (string key in templateKeywords.Keys) { if (key.ToLower().Equals("{signature}")) { using (FileStream imageFile = new FileStream(tempIMGpath, FileMode.Create)) { byte[] bytes = System.Convert.FromBase64String(templateKeywords[key].Replace("data:image/jpeg;base64,", string.Empty)); imageFile.Write(bytes, 0, bytes.Length); imageFile.Flush(); imageFile.Dispose(); } Novacode.Image img = _template.AddImage(tempIMGpath); Picture pic1 = img.CreatePicture(); Novacode.Paragraph p1 = _template.InsertParagraph(); p1.InsertPicture(pic1); _template.ReplaceText(key, ""); } else { _template.ReplaceText(key, templateKeywords[key]); } } } _template.SaveAs(tempDOCpath); Aspose.Words.Document doc = new Aspose.Words.Document(tempDOCpath); doc.Save(tempPDFpath); //doc.Remove(); /*Microsoft.Office.Interop.Word.Document wordDocument; * Application appWord = new Application(); * wordDocument = appWord.Documents.Open(tempDOCpath); * wordDocument.ExportAsFixedFormat(tempPDFpath, WdExportFormat.wdExportFormatPDF); * * wordDocument.Close();*/ ms.Flush(); ms.Close(); return(tempPDFpath); }
static void Main(string[] args) { string fileName = @"SoftUniContest.docx"; string headlineText = "SoftUni OOP Game Contest"; string paraOne = "" + "SoftUni is organazing a contest for the best role playing game from the OOP teamwork projects. " + "The winning teams will receive a grand prize!"; //Title styling var headLineFormat = new Formatting(); headLineFormat.FontFamily = new System.Drawing.FontFamily("Arial Black"); headLineFormat.Size = 22D; headLineFormat.Position = 12; headLineFormat.Bold = true; //Bottom styling var bottom = new Formatting(); bottom.FontFamily = new System.Drawing.FontFamily("Arial Black"); bottom.Size = 16D; bottom.Position = 12; bottom.Bold = true; //Handshake format var handshakeFormat = new Formatting(); handshakeFormat.FontFamily = new System.Drawing.FontFamily("Arial Black"); handshakeFormat.Size = 22D; handshakeFormat.Position = 12; handshakeFormat.Bold = true; handshakeFormat.UnderlineStyle = UnderlineStyle.singleLine; //Paragraph Format var paraFormat = new Formatting(); paraFormat.FontFamily = new System.Drawing.FontFamily("Calibri"); paraFormat.Size = 14D; var doc = DocX.Create(fileName); Paragraph title = doc.InsertParagraph(headlineText, false, headLineFormat); title.Alignment = Alignment.center; //Create Image + Insert It using (MemoryStream ms = new MemoryStream()) { System.Drawing.Image myImg = System.Drawing.Image.FromFile(@"rpg-game.png"); myImg.Save(ms, myImg.RawFormat); ms.Seek(0, SeekOrigin.Begin); Novacode.Image img = doc.AddImage(ms); Paragraph p = doc.InsertParagraph("", false); Picture pic1 = img.CreatePicture(); pic1.Height = 250; pic1.Width = 650; p.InsertPicture(pic1, 0); doc.Save(); } doc.InsertParagraph(Environment.NewLine); doc.InsertParagraph(paraOne, false, paraFormat); doc.InsertParagraph("The Game should be:", false, paraFormat); doc.InsertParagraph(" -Properly Structured and allow good OOP practices", false, paraFormat); doc.InsertParagraph(" -Awesome", false, paraFormat); doc.InsertParagraph(" -..Very Awesome", false, paraFormat); doc.InsertParagraph(Environment.NewLine); //Add Table Table t = doc.AddTable(4, 3); t.Alignment = Alignment.center; t.Design = TableDesign.LightGridAccent1; for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { t.Rows[j].Cells[i].Width = 200; } } t.Rows[0].Cells[0].InsertParagraph("Team", false, paraFormat); t.Rows[0].Cells[1].InsertParagraph("Game", false, paraFormat); t.Rows[0].Cells[2].InsertParagraph("Points", false, paraFormat); t.Rows[1].Cells[0].InsertParagraph("-", false, paraFormat); t.Rows[1].Cells[1].InsertParagraph("-", false, paraFormat); t.Rows[1].Cells[2].InsertParagraph("-", false, paraFormat); t.Rows[2].Cells[0].InsertParagraph("-", false, paraFormat); t.Rows[2].Cells[1].InsertParagraph("-", false, paraFormat); t.Rows[2].Cells[2].InsertParagraph("-", false, paraFormat); t.Rows[3].Cells[0].InsertParagraph("-", false, paraFormat); t.Rows[3].Cells[1].InsertParagraph("-", false, paraFormat); t.Rows[3].Cells[2].InsertParagraph("-", false, paraFormat); // Insert the Table into the document. doc.InsertTable(t); doc.InsertParagraph(Environment.NewLine); doc.InsertParagraph(Environment.NewLine); doc.InsertParagraph(Environment.NewLine); //Bottom Paragraph title1 = doc.InsertParagraph("The top 3 teams will receive a SPECTACULAR prize: ", false, bottom); title1.Alignment = Alignment.center; Paragraph title2 = doc.InsertParagraph("A HANDSHAKE FROM NAKOV", false, handshakeFormat); title2.Color(System.Drawing.Color.Blue); title2.Alignment = Alignment.center; doc.Save(); Process.Start("WINWORD.EXE", fileName); }
// Create an invoice template. private static DocX CreateInvoiceTemplate() { // Create a new document. DocX document = DocX.Create(@"docs\InvoiceTemplate.docx"); // Create a table for layout purposes (This table will be invisible). Table layout_table = document.InsertTable(2, 2); layout_table.Design = TableDesign.TableNormal; layout_table.AutoFit = AutoFit.Window; // Dark formatting Formatting dark_formatting = new Formatting(); dark_formatting.Bold = true; dark_formatting.Size = 12; dark_formatting.FontColor = Color.FromArgb(31, 73, 125); // Light formatting Formatting light_formatting = new Formatting(); light_formatting.Italic = true; light_formatting.Size = 11; light_formatting.FontColor = Color.FromArgb(79, 129, 189); #region Company Name // Get the upper left Paragraph in the layout_table. Paragraph upper_left_paragraph = layout_table.Rows[0].Cells[0].Paragraphs[0]; // Create a custom property called company_name CustomProperty company_name = new CustomProperty("company_name", "Company Name"); // Insert a field of type doc property (This will display the custom property 'company_name') layout_table.Rows[0].Cells[0].Paragraphs[0].InsertDocProperty(company_name, f: dark_formatting); // Force the next text insert to be on a new line. upper_left_paragraph.InsertText("\n", false); #endregion #region Company Slogan // Create a custom property called company_slogan CustomProperty company_slogan = new CustomProperty("company_slogan", "Company slogan goes here."); // Insert a field of type doc property (This will display the custom property 'company_slogan') upper_left_paragraph.InsertDocProperty(company_slogan, f: light_formatting); #endregion #region Company Logo // Get the upper right Paragraph in the layout_table. Paragraph upper_right_paragraph = layout_table.Rows[0].Cells[1].Paragraphs[0]; // Add a template logo image to this document. Novacode.Image logo = document.AddImage(@"images\logo_template.png"); // Insert this template logo into the upper right Paragraph. upper_right_paragraph.InsertPicture(logo.CreatePicture()); upper_right_paragraph.Alignment = Alignment.right; #endregion // Custom properties cannot contain newlines, so the company address must be split into 3 custom properties. #region Hired Company Address // Create a custom property called company_address_line_one CustomProperty hired_company_address_line_one = new CustomProperty("hired_company_address_line_one", "Street Address,"); // Get the lower left Paragraph in the layout_table. Paragraph lower_left_paragraph = layout_table.Rows[1].Cells[0].Paragraphs[0]; lower_left_paragraph.InsertText("TO:\n", false, dark_formatting); // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_one') lower_left_paragraph.InsertDocProperty(hired_company_address_line_one, f: light_formatting); // Force the next text insert to be on a new line. lower_left_paragraph.InsertText("\n", false); // Create a custom property called company_address_line_two CustomProperty hired_company_address_line_two = new CustomProperty("hired_company_address_line_two", "City,"); // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_two') lower_left_paragraph.InsertDocProperty(hired_company_address_line_two, f: light_formatting); // Force the next text insert to be on a new line. lower_left_paragraph.InsertText("\n", false); // Create a custom property called company_address_line_two CustomProperty hired_company_address_line_three = new CustomProperty("hired_company_address_line_three", "Zip Code"); // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_three') lower_left_paragraph.InsertDocProperty(hired_company_address_line_three, f: light_formatting); #endregion #region Date & Invoice number // Get the lower right Paragraph from the layout table. Paragraph lower_right_paragraph = layout_table.Rows[1].Cells[1].Paragraphs[0]; CustomProperty invoice_date = new CustomProperty("invoice_date", DateTime.Today.Date.ToString("d")); lower_right_paragraph.InsertText("Date: ", false, dark_formatting); lower_right_paragraph.InsertDocProperty(invoice_date, f: light_formatting); CustomProperty invoice_number = new CustomProperty("invoice_number", 1); lower_right_paragraph.InsertText("\nInvoice: ", false, dark_formatting); lower_right_paragraph.InsertText("#", false, light_formatting); lower_right_paragraph.InsertDocProperty(invoice_number, f: light_formatting); lower_right_paragraph.Alignment = Alignment.right; #endregion // Insert an empty Paragraph between two Tables, so that they do not touch. document.InsertParagraph(string.Empty, false); // This table will hold all of the invoice data. Table invoice_table = document.InsertTable(4, 4); invoice_table.Design = TableDesign.LightShadingAccent1; invoice_table.Alignment = Alignment.center; // A nice thank you Paragraph. Paragraph thankyou = document.InsertParagraph("\nThank you for your business, we hope to work with you again soon.", false, dark_formatting); thankyou.Alignment = Alignment.center; #region Hired company details CustomProperty hired_company_details_line_one = new CustomProperty("hired_company_details_line_one", "Street Address, City, ZIP Code"); CustomProperty hired_company_details_line_two = new CustomProperty("hired_company_details_line_two", "Phone: 000-000-0000, Fax: 000-000-0000, e-mail: [email protected]"); Paragraph companyDetails = document.InsertParagraph(string.Empty, false); companyDetails.InsertDocProperty(hired_company_details_line_one, f: light_formatting); companyDetails.InsertText("\n", false); companyDetails.InsertDocProperty(hired_company_details_line_two, f: light_formatting); companyDetails.Alignment = Alignment.center; #endregion // Return the document now that it has been created. return(document); }
/// <summary> /// Creates a document with a Hyperlink, an Image and a Table. /// </summary> private static void HyperlinksImagesTables() { Console.WriteLine("\tHyperlinksImagesTables()"); // Create a document. using (DocX document = DocX.Create(@"docs\HyperlinksImagesTables.docx")) { // Add a hyperlink into the document. Hyperlink link = document.AddHyperlink("link", new Uri("http://www.google.com")); // Add a Table into the document. Table table = document.AddTable(2, 2); table.Design = TableDesign.ColorfulGridAccent2; table.Alignment = Alignment.center; table.Rows[0].Cells[0].Paragraphs[0].Append("1"); table.Rows[0].Cells[1].Paragraphs[0].Append("2"); table.Rows[1].Cells[0].Paragraphs[0].Append("3"); table.Rows[1].Cells[1].Paragraphs[0].Append("4"); Row newRow = table.InsertRow(table.Rows[1]); newRow.ReplaceText("4", "5"); // Add an image into the document. Novacode.Image image = document.AddImage(@"images\logo_template.png"); // Create a picture (A custom view of an Image). Picture picture = image.CreatePicture(); picture.Rotation = 10; picture.SetPictureShape(BasicShapes.cube); // Insert a new Paragraph into the document. Paragraph title = document.InsertParagraph().Append("Test").FontSize(20).Font(new FontFamily("Comic Sans MS")); title.Alignment = Alignment.center; // Insert a new Paragraph into the document. Paragraph p1 = document.InsertParagraph(); // Append content to the Paragraph p1.AppendLine("This line contains a ").Append("bold").Bold().Append(" word."); p1.AppendLine("Here is a cool ").AppendHyperlink(link).Append("."); p1.AppendLine(); p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?"); p1.AppendLine(); p1.AppendLine("Can you check this Table of figures for me?"); p1.AppendLine(); // Insert the Table after Paragraph 1. p1.InsertTableAfterSelf(table); // Insert a new Paragraph into the document. Paragraph p2 = document.InsertParagraph(); // Append content to the Paragraph. p2.AppendLine("Is it correct?"); // Save this document. document.Save(); Console.WriteLine("\tCreated: docs\\HyperlinksImagesTables.docx\n"); } }
public void CreateFlyer() { var doc = DocX.Create(this.fileName); var headLineText = "SoftUni OOP Game Contest"; var headlineFormat = new Formatting(); headlineFormat.Size = 18D; headlineFormat.FontFamily = new System.Drawing.FontFamily("Arial Black"); Paragraph headLine = doc.InsertParagraph(headLineText, false, headlineFormat); headLine.Alignment = Alignment.center; Paragraph imageParagraph = doc.InsertParagraph(); Novacode.Image img = doc.AddImage("rpg-game.png"); imageParagraph.InsertPicture(img.CreatePicture(230, 600)); Paragraph emptyLine = doc.InsertParagraph(); Paragraph firstParagraph = doc.InsertParagraph(); firstParagraph.Append("SoftUni is organizing a contest for the best ").Font(new System.Drawing.FontFamily("Calibri")).FontSize(9d) .Append("role playing game").Bold().Font(new System.Drawing.FontFamily("Calibri")).FontSize(9d) .Append(" from the OOP teamwork projects. The winning teams will receive a ").Font(new System.Drawing.FontFamily("Calibri")).FontSize(9d) .Append("grand prize").UnderlineStyle(UnderlineStyle.singleLine).Bold().Font(new System.Drawing.FontFamily("Calibri")).FontSize(9d) .Append(" !").Font(new System.Drawing.FontFamily("Calibri")).FontSize(9d); Paragraph secondParagraph = doc.InsertParagraph("This game should be:").Font(new System.Drawing.FontFamily("Calibri")).FontSize(9d); List list = doc.AddList(null, 0, ListItemType.Bulleted); doc.AddListItem(list, "Properly structured and follow all good OOP practices", 0, ListItemType.Bulleted); doc.AddListItem(list, "Awesome", 0, ListItemType.Bulleted); doc.AddListItem(list, "..Very Awesome", 0, ListItemType.Bulleted); doc.InsertList(list); Table table = doc.AddTable(4, 3); table.Alignment = Alignment.center; for (int i = 0; i < 3; i++) { table.Rows[0].Cells[i].FillColor = Color.RoyalBlue; } table.Rows[0].Cells[0].InsertParagraph("Team").Color(Color.White).Bold().Alignment = Alignment.center; table.Rows[0].Cells[1].InsertParagraph("Game").Color(Color.White).Bold().Alignment = Alignment.center; table.Rows[0].Cells[2].InsertParagraph("Points").Color(Color.White).Bold().Alignment = Alignment.center; for (int i = 1; i < table.RowCount; i++) { for (int j = 0; j < table.ColumnCount; j++) { table.Rows[i].Cells[j].InsertParagraph("-").Bold().Alignment = Alignment.center; } } doc.InsertParagraph(); doc.InsertTable(table); doc.InsertParagraph(); Paragraph preFinal = doc.InsertParagraph(); preFinal.Append("The top 3 teams will receive a ").Append("SPECTACULAR").Bold().Append(" prize:").Alignment = Alignment.center; doc.InsertParagraph("A HANDSHAKE FROM NAKOV").Bold().UnderlineStyle(UnderlineStyle.singleLine).Color(Color.DarkBlue).FontSize(20D).Alignment = Alignment.center; doc.Save(); Process.Start("WINWORD.EXE", this.fileName); }
public void CreateSampleDocument() { // Modify to suit your machine: //string fileName = @"C:\temp\DocXExample4.docx"; string fileName = difftooldir + "\\" + System.DateTime.Now.ToString("yyMMddHHmmss") + "diffreport" + ".docx"; // Create a document in memory: var doc = DocX.Create(fileName); //2nd subheading formatting Formatting heading2 = new Formatting(); heading2.Bold = false; heading2.Size = 16; heading2.Bold = true; heading2.UnderlineStyle = UnderlineStyle.singleLine; heading2.FontColor = System.Drawing.Color.DarkOrange; Paragraph empty = doc.InsertParagraph("", false); //Main Heading Formatting headingformat = new Formatting(); headingformat.Bold = true; headingformat.Size = 48; headingformat.FontColor = System.Drawing.Color.DarkOrange; Paragraph heading = doc.InsertParagraph("Sequencer results compare.", false, headingformat); heading.Color(System.Drawing.Color.DarkOrange); doc.InsertParagraph(" ", false); doc.InsertParagraph(" ", false); //Foreword second heading //Paragraph headingsub = doc.InsertParagraph("UUT under test information.", false, heading2); //Foreword formating Formatting foreword = new Formatting(); foreword.Bold = false; foreword.Size = 12; foreword.FontColor = System.Drawing.Color.Black; Paragraph headingsub = doc.InsertParagraph("1.1 UUT under test information.", false, heading2); headingsub.Heading(HeadingType.Heading2); Paragraph forworduut = doc.InsertParagraph(uutdetail, false, foreword); //Foreword baseline heading empty = doc.InsertParagraph("", false); //Novacode.HeadingType.Heading1 Paragraph headingbaseline = doc.InsertParagraph("1.2 Baseline test information.", false, heading2); Paragraph forwordbasline = doc.InsertParagraph(baselinedetail, false, foreword); //new page doc.InsertSectionPageBreak(false); //new page //Efficiency compare Images of Novacode.Image img = doc.AddImage(difftooldir + "\\" + "Efficiency.jpg"); // Insert a paragrpah: Paragraph p0 = doc.InsertParagraph ("1.3 The sum of the difference in efficiency of the two unit under test.", false, heading2); //Efficiency compare Images of Paragraph p = doc.InsertParagraph(" ", false); p.AppendLine("The Orange marker is the sum of the difference between the baseline unit and the UUT. "); p.Append("Every orange marker indicates a different phase angle. "); p.Append("If there is a red cross it means the total sum was higher than 15 and that "); p.Append("there is some measured points that need closer inspecting. "); //#region #region pic1 Picture pic1 = img.CreatePicture(); int w = 0; p.InsertPicture(pic1, w); #endregion //This is the Idc comapre region //Novacode.Image imgIdc0 = doc.AddImage(@"C:\temp\DC current0°.jpg"); Novacode.Image imgIdc0 = doc.AddImage(difftooldir + "\\" + "DC current0°.jpg"); Novacode.Image imgIdcn45 = doc.AddImage(difftooldir + "\\" + "DC current-45°.jpg"); Novacode.Image imgIdcn30 = doc.AddImage(difftooldir + "\\" + "DC current-30°.jpg"); Novacode.Image imgIdcn15 = doc.AddImage(difftooldir + "\\" + "DC current-15°.jpg"); Novacode.Image imgIdc15 = doc.AddImage(difftooldir + "\\" + "DC current15°.jpg"); Novacode.Image imgIdc30 = doc.AddImage(difftooldir + "\\" + "DC current30°.jpg"); Novacode.Image imgIdc45 = doc.AddImage(difftooldir + "\\" + "DC current45°.jpg"); // Insert a pagebreak: doc.InsertSectionPageBreak(false); doc.InsertParagraph("1.4 Comparative plots of the DC current at every phase angle.", false, heading2); doc.InsertParagraph(""); Paragraph p3 = doc.InsertParagraph("The baseline values are in black and the orange crosses are the UUT."); p3.AppendLine("If the is a red cross in the graph then the reported measurement was below 0.1A,"); p3.Append("this means that the inverter probably did not start up at that point."); p3.AppendLine(""); p3.AppendLine(""); //Efficiency compare Images of doc.InsertParagraph("", false); //Efficiency picture area here Paragraph p2 = doc.InsertParagraph(" ", false); #region picidc Picture picIdc0 = imgIdc0.CreatePicture(); Picture picIdcn45 = imgIdcn45.CreatePicture(); Picture picIdcn30 = imgIdcn30.CreatePicture(); Picture picIdcn15 = imgIdcn15.CreatePicture(); Picture picIdc15 = imgIdc15.CreatePicture(); Picture picIdc30 = imgIdc30.CreatePicture(); Picture picIdc45 = imgIdc45.CreatePicture(); //int w1 = 0; p2.InsertPicture(picIdc0, 0); p2.InsertPicture(picIdcn45, 0); p2.InsertPicture(picIdcn30, 0); p2.InsertPicture(picIdcn15, 0); p2.InsertPicture(picIdc15, 0); p2.InsertPicture(picIdc30, 0); p2.InsertPicture(picIdc45, 0); #endregion //Vdc accuracy Novacode.Image imgvdcrep0 = doc.AddImage(difftooldir + "\\" + "Vdc0°.jpg"); Novacode.Image imgvdcrep45 = doc.AddImage(difftooldir + "\\" + "Vdc45°.jpg"); Novacode.Image imgvdcrep30 = doc.AddImage(difftooldir + "\\" + "Vdc30°.jpg"); Novacode.Image imgvdcrep15 = doc.AddImage(difftooldir + "\\" + "Vdc15°.jpg"); Novacode.Image imgvdcrepn15 = doc.AddImage(difftooldir + "\\" + "Vdc-15°.jpg"); Novacode.Image imgvdcrepn30 = doc.AddImage(difftooldir + "\\" + "Vdc-30°.jpg"); Novacode.Image imgvdcrepn45 = doc.AddImage(difftooldir + "\\" + "Vdc-45°.jpg"); // Insert a pagebreak: doc.InsertSectionPageBreak(false); doc.InsertParagraph("1.5 DC voltage accuracy at every phase angle.", false, heading2); doc.InsertParagraph(""); Paragraph p4 = doc.InsertParagraph("The baseline values are in black and the orange crosses are the UUT."); p4.AppendLine(""); p4.AppendLine(""); //Efficiency compare Images of doc.InsertParagraph("", false); Paragraph p5 = doc.InsertParagraph(" ", false); //# region vdc accuracy region #region picvdcacc p5.InsertPicture(imgvdcrep0.CreatePicture()); p5.InsertPicture(imgvdcrep45.CreatePicture()); p5.InsertPicture(imgvdcrep30.CreatePicture()); p5.InsertPicture(imgvdcrep15.CreatePicture()); p5.InsertPicture(imgvdcrepn15.CreatePicture()); p5.InsertPicture(imgvdcrepn30.CreatePicture()); p5.InsertPicture(imgvdcrepn45.CreatePicture()); #endregion //Idc accuracy Novacode.Image imgidcrep0 = doc.AddImage(difftooldir + "\\" + "Idc0°.jpg"); Novacode.Image imgidcrep45 = doc.AddImage(difftooldir + "\\" + "Idc45°.jpg"); Novacode.Image imgidcrep30 = doc.AddImage(difftooldir + "\\" + "Idc30°.jpg"); Novacode.Image imgidcrep15 = doc.AddImage(difftooldir + "\\" + "Idc15°.jpg"); Novacode.Image imgidcrepn15 = doc.AddImage(difftooldir + "\\" + "Idc-15°.jpg"); Novacode.Image imgidcrepn30 = doc.AddImage(difftooldir + "\\" + "Idc-30°.jpg"); Novacode.Image imgidcrepn45 = doc.AddImage(difftooldir + "\\" + "Idc-45°.jpg"); // Insert a pagebreak: doc.InsertSectionPageBreak(false); doc.InsertParagraph("1.6 DC current accuracy at every phase angle.", false, heading2); doc.InsertParagraph(""); doc.InsertParagraph("The baseline values are in black and the orange crosses are the UUT."); doc.InsertParagraph(""); doc.InsertParagraph(""); //Efficiency compare Images of doc.InsertParagraph("", false); Paragraph p7 = doc.InsertParagraph(" ", false); //# region vdc accuracy region #region picidcacc p7.InsertPicture(imgidcrep0.CreatePicture()); p7.InsertPicture(imgidcrep45.CreatePicture()); p7.InsertPicture(imgidcrep30.CreatePicture()); p7.InsertPicture(imgidcrep15.CreatePicture()); p7.InsertPicture(imgidcrepn15.CreatePicture()); p7.InsertPicture(imgidcrepn30.CreatePicture()); p7.InsertPicture(imgidcrepn45.CreatePicture()); #endregion //Wac accuracy Novacode.Image Wac0 = doc.AddImage(difftooldir + "\\" + "Wac0°.jpg"); Novacode.Image Wac45 = doc.AddImage(difftooldir + "\\" + "Wac45°.jpg"); Novacode.Image Wac30 = doc.AddImage(difftooldir + "\\" + "Wac30°.jpg"); Novacode.Image Wac15 = doc.AddImage(difftooldir + "\\" + "Wac15°.jpg"); Novacode.Image Wacn15 = doc.AddImage(difftooldir + "\\" + "Wac-15°.jpg"); Novacode.Image Wacn30 = doc.AddImage(difftooldir + "\\" + "Wac-30°.jpg"); Novacode.Image Wacn45 = doc.AddImage(difftooldir + "\\" + "Wac-45°.jpg"); // Insert a pagebreak: doc.InsertSectionPageBreak(false); doc.InsertParagraph("1.7 AC watts comparison at every phase angle.", false, heading2); doc.InsertParagraph(""); doc.InsertParagraph("The baseline values are in black and the orange crosses are the UUT."); doc.InsertParagraph(""); doc.InsertParagraph(""); //Efficiency compare Images of doc.InsertParagraph("", false); Paragraph p8 = doc.InsertParagraph(" ", false); //# region vdc accuracy region #region Wac p8.InsertPicture(Wac0.CreatePicture()); p8.InsertPicture(Wac45.CreatePicture()); p8.InsertPicture(Wac30.CreatePicture()); p8.InsertPicture(Wac15.CreatePicture()); p8.InsertPicture(Wacn15.CreatePicture()); p8.InsertPicture(Wacn30.CreatePicture()); p8.InsertPicture(Wacn45.CreatePicture()); #endregion //Idc accuracy Novacode.Image VAR0 = doc.AddImage(difftooldir + "\\" + "VAR0°.jpg"); Novacode.Image VAR45 = doc.AddImage(difftooldir + "\\" + "VAR45°.jpg"); Novacode.Image VAR30 = doc.AddImage(difftooldir + "\\" + "VAR30°.jpg"); Novacode.Image VAR15 = doc.AddImage(difftooldir + "\\" + "VAR15°.jpg"); Novacode.Image VARn15 = doc.AddImage(difftooldir + "\\" + "VAR-15°.jpg"); Novacode.Image VARn30 = doc.AddImage(difftooldir + "\\" + "VAR-30°.jpg"); Novacode.Image VARn45 = doc.AddImage(difftooldir + "\\" + "VAR-45°.jpg"); // Insert a pagebreak: doc.InsertSectionPageBreak(false); doc.InsertParagraph("1.8 AC VAR comparison at every phase angle.", false, heading2); doc.InsertParagraph(""); doc.InsertParagraph("The baseline values are in black and the orange crosses are the UUT."); doc.InsertParagraph(""); //Efficiency compare Images of doc.InsertParagraph("", false); Paragraph p9 = doc.InsertParagraph(" ", false); //# region vdc accuracy region #region VAR p9.InsertPicture(VAR0.CreatePicture()); p9.InsertPicture(VAR45.CreatePicture()); p9.InsertPicture(VAR30.CreatePicture()); p9.InsertPicture(VAR15.CreatePicture()); p9.InsertPicture(VARn15.CreatePicture()); p9.InsertPicture(VARn30.CreatePicture()); p9.InsertPicture(VARn45.CreatePicture()); #endregion //Wac accuracy Novacode.Image Vac0 = doc.AddImage(difftooldir + "\\" + "Vac0°.jpg"); Novacode.Image Vac45 = doc.AddImage(difftooldir + "\\" + "Vac45°.jpg"); Novacode.Image Vac30 = doc.AddImage(difftooldir + "\\" + "Vac30°.jpg"); Novacode.Image Vac15 = doc.AddImage(difftooldir + "\\" + "Vac15°.jpg"); Novacode.Image Vacn15 = doc.AddImage(difftooldir + "\\" + "Vac-15°.jpg"); Novacode.Image Vacn30 = doc.AddImage(difftooldir + "\\" + "Vac-30°.jpg"); Novacode.Image Vacn45 = doc.AddImage(difftooldir + "\\" + "Vac-45°.jpg"); // Insert a pagebreak: doc.InsertSectionPageBreak(false); doc.InsertParagraph("1.9 AC volts comparison at every phase angle.", false, heading2); doc.InsertParagraph(""); doc.InsertParagraph("The baseline values are in black and the orange crosses are the UUT."); doc.InsertParagraph(""); doc.InsertParagraph(""); //Efficiency compare Images of doc.InsertParagraph("", false); Paragraph p10 = doc.InsertParagraph(" ", false); //# region vdc accuracy region #region Wac p10.InsertPicture(Vac0.CreatePicture()); p10.InsertPicture(Vac45.CreatePicture()); p10.InsertPicture(Vac30.CreatePicture()); p10.InsertPicture(Vac15.CreatePicture()); p10.InsertPicture(Vacn15.CreatePicture()); p10.InsertPicture(Vacn30.CreatePicture()); p10.InsertPicture(Vacn45.CreatePicture()); #endregion // Save to the output directory: doc.Save(); // Open in Word: //Process.Start("WINWORD.EXE", fileName); }