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 }
//插入图片,插入的位置可以调整的,不过这里没写 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. }
/// <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); }
//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; }
private void UpdateDoc(DocX doc, FileContent fileCnt) { //1、页眉 //logo if (fileCnt.logo.IsNotEmpty() && File.Exists(fileCnt.logo)) { Novacode.Image img = doc.AddImage(fileCnt.logo); AddLogoToHeader(doc.Headers.odd, img); AddLogoToHeader(doc.Headers.first, img, 100, 100); } doc.ReplaceText("A2", fileCnt.filename); doc.ReplaceText("A3", fileCnt.filecode); doc.ReplaceText("A4", fileCnt.versioncode); doc.ReplaceText("A5", fileCnt.efdate); //2、表格 doc.ReplaceText("A6", fileCnt.draftdept); doc.ReplaceText("A7", fileCnt.checkdept1); doc.ReplaceText("A8", fileCnt.checkdept2); doc.ReplaceText("A9", fileCnt.checkdept3); doc.ReplaceText("A10", fileCnt.approver); doc.ReplaceText("A11", "1"); doc.ReplaceText("A12", fileCnt.remark); doc.ReplaceText("A13", fileCnt.writer); doc.Save(); }
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> /// Load image into document. /// Required before producing a Picture for the document. /// </summary> public TemplGraphic Load(DocX doc) { if (!Loaded) { Image = doc.AddImage(Stream); Loaded = true; } return(this); }
public TemplGraphic Load(DocX doc) { if (!Loaded) { Image = doc.AddImage(Data); Loaded = true; } return this; }
/// <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); }
private Stream CreateLabel(int id) { var model = new ProfileBoxModel(); var profileBox = _profileBoxService.GetById(id); string label = profileBox.Name.ToUpper(); string profileCount = ""; if (!profileBox.ProfileType.Scanned) { profileCount = profileBox.ProfileCount.ToString(); } else { var profiles = _profileService.SearchProfilesByStatus(id, 0, 1, int.MaxValue, null, null); profileCount = profiles.Count(x => x.StatusId != (short)ProfileStatus.Deleted).ToString(); } string filePath = Server.MapPath(Url.Content("~/Template/Label.docx")); DocX document = DocX.Load(filePath); var outputStream = new MemoryStream(); document.ReplaceText("{Label}", label); document.ReplaceText("{count}", profileCount); // get placeholder image Novacode.Image img = document.Images[0]; // create barcode encoder var barcodeWriter = new BarcodeWriter { Format = BarcodeFormat.CODE_128, Options = new EncodingOptions { PureBarcode = false, Height = 100, Width = 300, Margin = 10 } }; // create barcode image var bitmap = barcodeWriter.Write(label); // replace place holder image in document with barcode image bitmap.Save(img.GetStream(FileMode.Create, FileAccess.Write), ImageFormat.Png); document.SaveAs(outputStream); outputStream.Position = 0; document.Dispose(); return(outputStream); }
/// <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> /// Loads a document 'Input.docx' and writes the text 'Hello World' into the first imbedded Image. /// This code creates the file 'Output.docx'. /// </summary> static void ProgrammaticallyManipulateImbeddedImage() { Console.WriteLine("\tProgrammaticallyManipulateImbeddedImage()"); const string str = "Hello World"; // Open the document Input.docx. using (DocX document = DocX.Load(@"Input.docx")) { // Make sure this document has at least one Image. if (document.Images.Count() > 0) { Novacode.Image img = document.Images[0]; // Write "Hello World" into this Image. Bitmap b = new Bitmap(img.GetStream(FileMode.Open, FileAccess.ReadWrite)); /* * Get the Graphics object for this Bitmap. * The Graphics object provides functions for drawing. */ Graphics g = Graphics.FromImage(b); // Draw the string "Hello World". g.DrawString ( str, new Font("Tahoma", 20), Brushes.Blue, new PointF(0, 0) ); // Save this Bitmap back into the document using a Create\Write stream. b.Save(img.GetStream(FileMode.Create, FileAccess.Write), ImageFormat.Png); } else { Console.WriteLine("The provided document contains no Images."); } // Save this document as Output.docx. document.SaveAs(@"docs\Output.docx"); Console.WriteLine("\tCreated: docs\\Output.docx\n"); } }
/// <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; } }
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); }
/// <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, ""); } } }
/// <summary> /// Wraps an XElement as an Image /// </summary> /// <param name="i">The XElement i to wrap</param> internal Picture(DocX document, XElement i, Image img) : base(document, i) { picture_rels = new Dictionary<PackagePart, PackageRelationship>(); this.img = img; this.id = ( from e in Xml.Descendants() where e.Name.LocalName.Equals("blip") select e.Attribute(XName.Get("embed", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")).Value ).SingleOrDefault(); if (this.id == null) { this.id = ( from e in Xml.Descendants() where e.Name.LocalName.Equals("imagedata") select e.Attribute(XName.Get("id", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")).Value ).SingleOrDefault(); } this.name = ( from e in Xml.Descendants() let a = e.Attribute(XName.Get("name")) where (a != null) select a.Value ).FirstOrDefault(); if (this.name == null) { this.name = ( from e in Xml.Descendants() let a = e.Attribute(XName.Get("title")) where (a != null) select a.Value ).FirstOrDefault(); } this.descr = ( from e in Xml.Descendants() let a = e.Attribute(XName.Get("descr")) where (a != null) select a.Value ).FirstOrDefault(); this.cx = ( from e in Xml.Descendants() let a = e.Attribute(XName.Get("cx")) where (a != null) select int.Parse(a.Value) ).FirstOrDefault(); if (this.cx == 0) { XAttribute style = ( from e in Xml.Descendants() let a = e.Attribute(XName.Get("style")) where (a != null) select a ).FirstOrDefault(); string fromWidth = style.Value.Substring(style.Value.IndexOf("width:") + 6); var widthInt = ((double.Parse((fromWidth.Substring(0, fromWidth.IndexOf("pt"))).Replace(".", ","))) / 72.0) * 914400; cx = System.Convert.ToInt32(widthInt); } this.cy = ( from e in Xml.Descendants() let a = e.Attribute(XName.Get("cy")) where (a != null) select int.Parse(a.Value) ).FirstOrDefault(); if (this.cy == 0) { XAttribute style = ( from e in Xml.Descendants() let a = e.Attribute(XName.Get("style")) where (a != null) select a ).FirstOrDefault(); string fromHeight = style.Value.Substring(style.Value.IndexOf("height:") + 7); var heightInt = ((double.Parse((fromHeight.Substring(0, fromHeight.IndexOf("pt"))).Replace(".", ","))) / 72.0) * 914400; cy = System.Convert.ToInt32(heightInt); } this.xfrm = ( from d in Xml.Descendants() where d.Name.LocalName.Equals("xfrm") select d ).SingleOrDefault(); this.prstGeom = ( from d in Xml.Descendants() where d.Name.LocalName.Equals("prstGeom") select d ).SingleOrDefault(); if (xfrm != null) this.rotation = xfrm.Attribute(XName.Get("rot")) == null ? 0 : uint.Parse(xfrm.Attribute(XName.Get("rot")).Value); }
/// <summary> /// Wraps an XElement as an Image /// </summary> /// <param name="i">The XElement i to wrap</param> internal Picture(DocX document, XElement i, Image img):base(document, i) { picture_rels = new Dictionary<PackagePart, PackageRelationship>(); this.img = img; this.id = ( from e in Xml.Descendants() where e.Name.LocalName.Equals("blip") select e.Attribute(XName.Get("embed", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")).Value ).Single(); this.name = ( from e in Xml.Descendants() let a = e.Attribute(XName.Get("name")) where (a != null) select a.Value ).First(); this.descr = ( from e in Xml.Descendants() let a = e.Attribute(XName.Get("descr")) where (a != null) select a.Value ).FirstOrDefault(); this.cx = ( from e in Xml.Descendants() let a = e.Attribute(XName.Get("cx")) where (a != null) select int.Parse(a.Value) ).First(); this.cy = ( from e in Xml.Descendants() let a = e.Attribute(XName.Get("cy")) where (a != null) select int.Parse(a.Value) ).First(); this.xfrm = ( from d in Xml.Descendants() where d.Name.LocalName.Equals("xfrm") select d ).Single(); this.prstGeom = ( from d in Xml.Descendants() where d.Name.LocalName.Equals("prstGeom") select d ).Single(); this.rotation = xfrm.Attribute(XName.Get("rot")) == null ? 0 : uint.Parse(xfrm.Attribute(XName.Get("rot")).Value); }
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 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); }
/// <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"); } }
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); }