static Document _createDocument <T>(IEnumerable <T> items, ArrayToPdfScheme <T> scheme) { var document = new Document(); document.UseCmykColor = true; document.Info.Title = scheme.Title; document.Info.Subject = scheme.Subject; document.Info.Author = scheme.Author; document.DefaultPageSetup.PageFormat = (PageFormat)scheme.PageFormat; document.DefaultPageSetup.Orientation = (Orientation)scheme.PageOrientation; document.DefaultPageSetup.HeaderDistance = Unit.FromMillimeter(scheme.PageMarginTop); document.DefaultPageSetup.FooterDistance = Unit.FromMillimeter(scheme.PageMarginBottom); document.DefaultPageSetup.TopMargin = Unit.FromMillimeter(scheme.PageMarginTop + (string.IsNullOrWhiteSpace(scheme.Header) ? 0 : scheme.HeaderHeight)); document.DefaultPageSetup.RightMargin = Unit.FromMillimeter(scheme.PageMarginRight + _tableLeftBias); document.DefaultPageSetup.BottomMargin = Unit.FromMillimeter(scheme.PageMarginBottom + (string.IsNullOrWhiteSpace(scheme.Footer) ? 0 : scheme.FooterHeight)); document.DefaultPageSetup.LeftMargin = Unit.FromMillimeter(scheme.PageMarginLeft - _tableLeftBias); Unit width, height; PageSetup.GetPageSize(document.DefaultPageSetup.PageFormat, out width, out height); document.DefaultPageSetup.PageWidth = width; document.DefaultPageSetup.PageHeight = height; var innerWidth = Unit.FromPoint(document.DefaultPageSetup.GetWidth() - document.DefaultPageSetup.LeftMargin - document.DefaultPageSetup.RightMargin); _addStyles(document, innerWidth); _addSection(document); _addHeader(document, innerWidth, scheme); _addFooter(document, innerWidth, scheme); _addTable(document, innerWidth, items, scheme); return(document); }
public static Unit GetWidth(Section section) { Unit pageWidth; Unit _; PageSetup.GetPageSize(section.PageSetup.PageFormat, out pageWidth, out _); return(pageWidth - section.PageSetup.LeftMargin - section.PageSetup.RightMargin); }
public static double PageWidth(this Document document) { PageSetup.GetPageSize(document.DefaultPageSetup.PageFormat, out Unit width, out Unit height); if (document.DefaultPageSetup.Orientation == Orientation.Landscape) { Utils.Swap <Unit>(ref width, ref height); } return(width.Point - document.DefaultPageSetup.LeftMargin.Point - document.DefaultPageSetup.RightMargin.Point); }
/// <summary> /// Find section useful with /// </summary> /// <param name="section">Migradoc section to set</param> /// <returns></returns> public static Unit getSectionWith(Section section) { Unit width; Unit height; PageSetup.GetPageSize(section.PageSetup.PageFormat, out width, out height); if (section.PageSetup.Orientation == Orientation.Landscape) { var tmp = width; width = height; height = tmp; } return(width - section.PageSetup.LeftMargin - section.PageSetup.RightMargin); }
private static void FormatTable(Table table, Section section) { table.LeftPadding = 5; table.TopPadding = 5; table.RightPadding = 5; table.BottomPadding = 5; table.Format.LeftIndent = Size.TableCellPadding; table.Format.RightIndent = Size.TableCellPadding; //get size info PageSetup.GetPageSize(PageFormat.Letter, out Unit width, out Unit height); Unit tableWidth = 0; foreach (Column col in table.Columns) { tableWidth += col.Width; } //indent to center table table.Rows.LeftIndent = Unit.FromCentimeter(width.Centimeter - section.PageSetup.LeftMargin.Centimeter - section.PageSetup.RightMargin.Centimeter - tableWidth.Centimeter) / 2; }
protected override void Setup(Section section) { section.PageSetup.PageFormat = PageFormat.A4; PageSetup.GetPageSize(section.PageSetup.PageFormat, out Unit pageWidth, out Unit pageHeight); section.PageSetup.PageWidth = pageWidth; section.PageSetup.PageHeight = pageHeight; section.PageSetup.LeftMargin = "2.2cm"; section.PageSetup.RightMargin = "2.2cm"; section.PageSetup.TopMargin = "2.2cm"; section.PageSetup.BottomMargin = "2.2cm"; var header = section.Headers.Primary.AddParagraph(); header.Style = "PageHeader"; header.Format.Alignment = ParagraphAlignment.Right; header.AddText("Sivu "); header.AddPageField(); header.AddText(" / "); header.AddNumPagesField(); }
private static Document CreateDocument(MarkdownDocument doc) { // Create a new MigraDoc document var document = new Document(); document.Info.Title = "Charaktere Karten"; document.Info.Subject = "Die Charakterkarten des spiels"; document.Info.Author = "Arbeitstitel Karthago"; document.Info.Keywords = "Karten, Charakter, Karthago"; document.DefaultPageSetup.PageFormat = PageFormat.A6; PageSetup.GetPageSize(PageFormat.A6, out var width, out var height); document.DefaultPageSetup.PageWidth = width; document.DefaultPageSetup.PageHeight = height; document.DefaultPageSetup.LeftMargin = new Unit(0.6, UnitType.Centimeter); document.DefaultPageSetup.RightMargin = new Unit(0.6, UnitType.Centimeter); document.DefaultPageSetup.BottomMargin = new Unit(0.6, UnitType.Centimeter); document.DefaultPageSetup.TopMargin = new Unit(0.6, UnitType.Centimeter); document.DefineStyles(); //Cover.DefineCover(document); //DefineTableOfContents(document); DefineContentSection(document); doc.Blocks.HandleBlocks(document); //DefineParagraphs(document); //DefineTables(document); //DefineCharts(document); return(document); }
private static void SetupDocument(Document document, Section section) { //Set Font var style = document.Styles["Normal"]; style.Font.Name = "Arial"; //Page Setup var pageSetup = document.DefaultPageSetup.Clone(); pageSetup.Orientation = Orientation.Portrait; Unit pageWidth, pageHeight; PageSetup.GetPageSize(PageFormat.Letter, out pageWidth, out pageHeight); pageSetup.LeftMargin = new Unit(0.5, UnitType.Inch); pageSetup.RightMargin = new Unit(0.5, UnitType.Inch); pageSetup.TopMargin = new Unit(0.27, UnitType.Inch); pageSetup.BottomMargin = new Unit(0.5, UnitType.Inch); pageSetup.PageWidth = pageWidth; pageSetup.PageHeight = pageHeight; pageSetup.FooterDistance = new Unit(-0.1, UnitType.Centimeter); pageSetup.HeaderDistance = new Unit(0.7, UnitType.Centimeter); pageSetup.DifferentFirstPageHeaderFooter = false; section.PageSetup = pageSetup; }
protected void FlattenPageSetup(PageSetup pageSetup, PageSetup refPageSetup) { if (pageSetup._pageWidth.IsNull && pageSetup._pageHeight.IsNull) { if (pageSetup._pageFormat.IsNull) { pageSetup._pageWidth = refPageSetup._pageWidth; pageSetup._pageHeight = refPageSetup._pageHeight; pageSetup._pageFormat = refPageSetup._pageFormat; } else { PageSetup.GetPageSize(pageSetup.PageFormat, out pageSetup._pageWidth, out pageSetup._pageHeight); } } else { Unit dummyUnit; if (pageSetup._pageWidth.IsNull) { if (pageSetup._pageFormat.IsNull) { pageSetup._pageHeight = refPageSetup._pageHeight; } else { PageSetup.GetPageSize(pageSetup.PageFormat, out dummyUnit, out pageSetup._pageHeight); } } else if (pageSetup._pageHeight.IsNull) { if (pageSetup._pageFormat.IsNull) { pageSetup._pageWidth = refPageSetup._pageWidth; } else { PageSetup.GetPageSize(pageSetup.PageFormat, out pageSetup._pageWidth, out dummyUnit); } } } // if (pageSetup.pageWidth.IsNull) // pageSetup.pageWidth = refPageSetup.pageWidth; // if (pageSetup.pageHeight.IsNull) // pageSetup.pageHeight = refPageSetup.pageHeight; // if (pageSetup.pageFormat.IsNull) // pageSetup.pageFormat = refPageSetup.pageFormat; if (pageSetup._sectionStart.IsNull) { pageSetup._sectionStart = refPageSetup._sectionStart; } if (pageSetup._orientation.IsNull) { pageSetup._orientation = refPageSetup._orientation; } if (pageSetup._topMargin.IsNull) { pageSetup._topMargin = refPageSetup._topMargin; } if (pageSetup._bottomMargin.IsNull) { pageSetup._bottomMargin = refPageSetup._bottomMargin; } if (pageSetup._leftMargin.IsNull) { pageSetup._leftMargin = refPageSetup._leftMargin; } if (pageSetup._rightMargin.IsNull) { pageSetup._rightMargin = refPageSetup._rightMargin; } if (pageSetup._headerDistance.IsNull) { pageSetup._headerDistance = refPageSetup._headerDistance; } if (pageSetup._footerDistance.IsNull) { pageSetup._footerDistance = refPageSetup._footerDistance; } if (pageSetup._oddAndEvenPagesHeaderFooter.IsNull) { pageSetup._oddAndEvenPagesHeaderFooter = refPageSetup._oddAndEvenPagesHeaderFooter; } if (pageSetup._differentFirstPageHeaderFooter.IsNull) { pageSetup._differentFirstPageHeaderFooter = refPageSetup._differentFirstPageHeaderFooter; } if (pageSetup._mirrorMargins.IsNull) { pageSetup._mirrorMargins = refPageSetup._mirrorMargins; } if (pageSetup._horizontalPageBreak.IsNull) { pageSetup._horizontalPageBreak = refPageSetup._horizontalPageBreak; } }
/// <summary> /// Create the PDF using the defined page size, label type and content provided /// Ensure you have added something first using either AddImage() or AddText() /// </summary> /// <returns></returns> public Stream CreatePDF() { //Get the page size MigraDoc.DocumentObjectModel.PageFormat pageSize; switch (_labelDefinition.PageSize) { case Enums.PageSize.LETTER: pageSize = MigraDoc.DocumentObjectModel.PageFormat.Letter; break; case Enums.PageSize.A4: pageSize = MigraDoc.DocumentObjectModel.PageFormat.A4; break; default: pageSize = MigraDoc.DocumentObjectModel.PageFormat.A4; break; } //Create a stream to write the PDF to var output = new MemoryStream(); //Create a new document object var document = new Document(); // Get the predefined style Normal. var style = document.Styles["Normal"]; // Because all styles are derived from Normal, the next line changes the // font of the whole document. Or, more exactly, it changes the font of // all styles and paragraphs that do not redefine the font. style.Font.Name = "SSans Pro Regular"; // Create a new style called Label based on style Normal. style = document.Styles.AddStyle("Label", "Normal"); style.ParagraphFormat.Alignment = ParagraphAlignment.Left; style.ParagraphFormat.Shading.Color = Colors.Black; Unit width, height; PageSetup.GetPageSize(pageSize, out width, out height); document.DefaultPageSetup.Orientation = Orientation.Portrait; document.DefaultPageSetup.PageFormat = pageSize; document.DefaultPageSetup.PageWidth = width; document.DefaultPageSetup.PageHeight = height; document.DefaultPageSetup.LeftMargin = Unit.FromMillimeter(_labelDefinition.PageMarginLeft); document.DefaultPageSetup.RightMargin = Unit.FromMillimeter(_labelDefinition.PageMarginRight); document.DefaultPageSetup.TopMargin = Unit.FromMillimeter(_labelDefinition.PageMarginTop); document.DefaultPageSetup.BottomMargin = Unit.FromMillimeter(_labelDefinition.PageMarginBottom); //Create a new table with label and gap columns var numOfCols = _labelDefinition.LabelsPerRow + (_labelDefinition.LabelsPerRow - 1); //Build the column width array, even numbered index columns will be gap columns var colWidths = new List <double>(); for (int i = 1; i <= numOfCols; i++) { if (i % 2 > 0) { colWidths.Add(_labelDefinition.Width); } else { //Even numbered columns are gap columns colWidths.Add(_labelDefinition.HorizontalGapWidth); } } // loop over the labels var rowNumber = 0; var colNumber = 0; Table tbl = null; Row row = null; Cell cell = null; foreach (var label in _labels) { if (rowNumber == 0) { var section = document.AddSection(); //Create page tbl = section.AddTable(); for (int i = 0; i < numOfCols; i++) { tbl.AddColumn(Unit.FromMillimeter(colWidths[i])); } row = tbl.AddRow(); rowNumber = 1; row.Height = Unit.FromMillimeter(_labelDefinition.Height); } cell = row.Cells[colNumber]; colNumber++; // add the label cell. label.GetLabelCell(cell); //Add to the row FormatCell(cell); //Create a empty cell to use as a gap if (colNumber < numOfCols) { colNumber++; // increment for the gap row } //On all but the last row, after the last column, add a gap row if needed if (colNumber == numOfCols && ((rowNumber) < _labelDefinition.LabelRowsPerPage && _labelDefinition.VerticalGapHeight > 0)) { row = tbl.AddRow(); row.Height = Unit.FromMillimeter(_labelDefinition.VerticalGapHeight); } if (colNumber == numOfCols && (rowNumber < _labelDefinition.LabelRowsPerPage && _labelDefinition.VerticalGapHeight <= 0)) { // add the row to the table and re-initialize row = tbl.AddRow(); row.Height = Unit.FromMillimeter(_labelDefinition.Height); } if (colNumber == numOfCols) { rowNumber++; colNumber = 0; } if (rowNumber > _labelDefinition.LabelRowsPerPage) { rowNumber = 0; colNumber = 0; } } if (colNumber < numOfCols) { // finish the row that was being built while (colNumber < numOfCols) { colNumber++; } } // make sure the last table gets added to the document if (rowNumber > 0) { } var pdfRenderer = new PdfDocumentRenderer(true); // Set the MigraDoc document. pdfRenderer.Document = document; // Create the PDF document. pdfRenderer.RenderDocument(); SetPrintScaling(pdfRenderer.PdfDocument); HideAllPages(pdfRenderer.PdfDocument); AddPrintExpireOnOpen(pdfRenderer.PdfDocument, DateTime.Now.AddMinutes(15)); pdfRenderer.Save(output, false); //Set the stream back to position 0 so we can use it when it's returned output.Position = 0; return(output); }
/// <summary> /// Creates PDF document from given content. See https://github.com/CommunityHiQ/Frends.Community.PdfFromTemplate /// </summary> /// <param name="outputFile"></param> /// <param name="content"></param> /// <param name="options"></param> /// <returns>Object { bool Success, string FileName, byte[] ResultAsByteArray }</returns> public static Output CreatePdf([PropertyTab] FileProperties outputFile, [PropertyTab] DocumentContent content, [PropertyTab] Options options) { try { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); DocumentDefinition docContent = JsonConvert.DeserializeObject <DocumentDefinition>(content.ContentJson); var document = new Document(); if (!string.IsNullOrWhiteSpace(docContent.Title)) { document.Info.Title = docContent.Title; } if (!string.IsNullOrWhiteSpace(docContent.Author)) { document.Info.Author = docContent.Author; } PageSetup.GetPageSize(docContent.PageSize.ConvertEnum <PageFormat>(), out Unit width, out Unit height); var section = document.AddSection(); SetupPage(section.PageSetup, width, height, docContent); // index for stylename var elementNumber = 0; // add page elements foreach (var pageElement in docContent.DocumentElements) { var styleName = $"style_{elementNumber}"; var style = document.Styles.AddStyle(styleName, "Normal"); switch (pageElement.ElementType) { case ElementTypeEnum.Paragraph: SetFont(style, ((ParagraphDefinition)pageElement).StyleSettings); SetParagraphStyle(style, ((ParagraphDefinition)pageElement).StyleSettings, false); AddTextContent(section, ((ParagraphDefinition)pageElement).Text, style); break; case ElementTypeEnum.Image: AddImage(section, (ImageDefinition)pageElement, width); break; case ElementTypeEnum.Table: SetFont(style, ((TableDefinition)pageElement).StyleSettings); SetParagraphStyle(style, ((TableDefinition)pageElement).StyleSettings, true); AddTable(section, (TableDefinition)pageElement, width, style); break; case ElementTypeEnum.PageBreak: section = document.AddSection(); SetupPage(section.PageSetup, width, height, docContent); break; default: break; } ++elementNumber; } string fileName = Path.Combine(outputFile.Directory, outputFile.FileName); int fileNameIndex = 1; while (File.Exists(fileName) && outputFile.FileExistsAction != FileExistsActionEnum.Overwrite) { switch (outputFile.FileExistsAction) { case FileExistsActionEnum.Error: throw new Exception($"File {fileName} already exists."); case FileExistsActionEnum.Rename: fileName = Path.Combine(outputFile.Directory, $"{Path.GetFileNameWithoutExtension(outputFile.FileName)}_({fileNameIndex}){Path.GetExtension(outputFile.FileName)}"); break; } fileNameIndex++; } // save document var pdfRenderer = new PdfDocumentRenderer(outputFile.Unicode) { Document = document }; pdfRenderer.RenderDocument(); if (outputFile.SaveToDisk) { if (!options.UseGivenCredentials) { pdfRenderer.PdfDocument.Save(fileName); } else { var domainAndUserName = GetDomainAndUserName(options.UserName); using (Impersonation.LogonUser(domainAndUserName[0], domainAndUserName[1], options.Password, LogonType.NewCredentials)) { pdfRenderer.PdfDocument.Save(fileName); } } } byte[] resultAsBytes = null; if (options.GetResultAsByteArray) { using (MemoryStream stream = new MemoryStream()) { pdfRenderer.PdfDocument.Save(stream, false); resultAsBytes = stream.ToArray(); } } return(new Output { Success = true, FileName = fileName, ResultAsByteArray = resultAsBytes }); } catch (Exception ex) { if (options.ThrowErrorOnFailure) { throw; } return(new Output { Success = false, ErrorMessage = ex.Message }); } }
public void MakeGiftCert(int itemID) { try { GiftCertificateInfo item; //load the item GiftCertificateController controller = new GiftCertificateController(); item = controller.GetGiftCert(itemId); string CertAmountWords = ""; string MailToAddressField = ""; string CertAmountNumber = ""; if (item != null) { if (item.PaypalPaymentState.ToString().Length == 0) { Response.Redirect(Globals.NavigateURL("Access Denied"), true); } TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; CertAmountWords = textInfo.ToTitleCase(NumberToWords(Int32.Parse(item.CertAmount.ToString())).ToString()).ToString() + " Dollars" + Environment.NewLine; CertAmountNumber = "$" + String.Format("{0:f2}", item.CertAmount).ToString(); MailToAddressField = item.MailTo.ToString() + Environment.NewLine + item.MailToAddress.ToString() + Environment.NewLine + item.MailToCity.ToString() + ", " + item.MailToState.ToString() + " " + item.MailToZip.ToString(); _CertNotes = item.Notes.ToString(); } string myPortalName = this.PortalSettings.PortalName.ToString(); Document document = new Document(); document.Info.Author = "Joseph Aucoin"; document.Info.Keywords = "Gift Certificate"; document.Info.Title = myPortalName.ToString() + " Gift Certificate"; // Get the A4 page size MigraDoc.DocumentObjectModel.Unit width, height; PageSetup.GetPageSize(PageFormat.Letter, out width, out height); // Add a section to the document and configure it such that it will be in the centre // of the page Section section = document.AddSection(); section.PageSetup.PageHeight = height; section.PageSetup.PageWidth = width; section.PageSetup.LeftMargin = 20; section.PageSetup.RightMargin = 10; section.PageSetup.TopMargin = 20; // height / 2; //++++++++++++++++++++++++++++++ //++++++++++++++++++++++++++++++ //++++++++++++++++++++++++++++++ // ADD LOGO string myLogo = PortalSettings.HomeDirectoryMapPath + _CertLogo.ToString(); // "Images\\Chapins-Logo.png"; MigraDoc.DocumentObjectModel.Shapes.Image image = section.Headers.Primary.AddImage(myLogo.ToString()); image.LockAspectRatio = true; image.RelativeVertical = MigraDoc.DocumentObjectModel.Shapes.RelativeVertical.Line; image.RelativeHorizontal = MigraDoc.DocumentObjectModel.Shapes.RelativeHorizontal.Margin; image.Top = MigraDoc.DocumentObjectModel.Shapes.ShapePosition.Top; image.Left = MigraDoc.DocumentObjectModel.Shapes.ShapePosition.Right; image.WrapFormat.Style = MigraDoc.DocumentObjectModel.Shapes.WrapStyle.Through; MigraDoc.DocumentObjectModel.Tables.Table HeaderTable = new MigraDoc.DocumentObjectModel.Tables.Table(); HeaderTable.Borders.Width = 0; // Default to show borders 1 pixel wide Column HeaderTable.LeftPadding = 10; HeaderTable.RightPadding = 10; HeaderTable.Borders.Left.Visible = false; HeaderTable.Borders.Right.Visible = false; // Add 1 columns float myColumnWidth = ((section.PageSetup.PageWidth - section.PageSetup.LeftMargin - section.PageSetup.RightMargin) / 2); // ((width / 2) - 10); MigraDoc.DocumentObjectModel.Tables.Column column0 = HeaderTable.AddColumn(myColumnWidth); MigraDoc.DocumentObjectModel.Tables.Row row1 = HeaderTable.AddRow(); row1.Cells[0].Elements.AddParagraph(_CertReturnAddress.ToString()); row1.Cells[0].Format.Alignment = ParagraphAlignment.Left; section.Add(HeaderTable); /// SPACING MigraDoc.DocumentObjectModel.Paragraph paragraph = section.AddParagraph(); paragraph.Format.LineSpacingRule = MigraDoc.DocumentObjectModel.LineSpacingRule.Exactly; paragraph.Format.LineSpacing = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(30.0); // section.Add(paragraph); //++++++++++++++++++++++++++++++ // ADD ANOTHER TABLE FOR MAIL TO ADDRESS // Create a table so that we can draw the horizontal lines MigraDoc.DocumentObjectModel.Tables.Table tableMailToAddress = new MigraDoc.DocumentObjectModel.Tables.Table(); tableMailToAddress.Borders.Width = 0; // Default to show borders 1 pixel wide Column tableMailToAddress.LeftPadding = 20; tableMailToAddress.RightPadding = 10; // float myColumnWidth100percent = (width - 10); var column = tableMailToAddress.AddColumn((section.PageSetup.PageWidth - section.PageSetup.LeftMargin - section.PageSetup.RightMargin)); double fontHeight = 20; Font font = new Font("Times New Roman", fontHeight); // Add a row with a single cell for the first line MigraDoc.DocumentObjectModel.Tables.Row row = tableMailToAddress.AddRow(); MigraDoc.DocumentObjectModel.Tables.Cell cell = row.Cells[0]; cell = row.Cells[0]; cell.Format.Font.Color = Colors.Black; cell.Format.Alignment = ParagraphAlignment.Left; cell.Format.Font.ApplyFont(font); cell.AddParagraph(MailToAddressField.ToString()); section.Add(tableMailToAddress); // ADD SPACER+++++++++++++++++++++++++++++++++++++++ MigraDoc.DocumentObjectModel.Paragraph paragraph1 = section.AddParagraph(); paragraph1.Format.LineSpacingRule = MigraDoc.DocumentObjectModel.LineSpacingRule.Exactly; paragraph1.Format.LineSpacing = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(20.0); // ADD ANOTHER TABLE FOR CERT // Create a table so that we can draw the horizontal lines MigraDoc.DocumentObjectModel.Tables.Table tableCert = new MigraDoc.DocumentObjectModel.Tables.Table(); tableCert.Borders.Width = 0; // Default to show borders 1 pixel wide Column tableCert.LeftPadding = 10; tableCert.RightPadding = 10; tableCert.Borders.Right.Visible = true; // float myColumnWidth100percent = (width - 10); float sectionWidth = section.PageSetup.PageWidth - section.PageSetup.LeftMargin - section.PageSetup.RightMargin; float columnWidth = sectionWidth; var columnCert = tableCert.AddColumn(columnWidth); columnCert.Format.Alignment = ParagraphAlignment.Center; double fontHeightCert = 30; Font fontCert = new Font("Times New Roman", fontHeightCert); // Add a row with a single cell for the first line MigraDoc.DocumentObjectModel.Tables.Row rowCert = tableCert.AddRow(); MigraDoc.DocumentObjectModel.Tables.Cell cellCert = rowCert.Cells[0]; cellCert.Format.Font.Color = Colors.Black; cellCert.Format.Font.ApplyFont(fontCert); cellCert.Borders.Left.Visible = false; cellCert.Borders.Right.Visible = false; cellCert.Borders.Bottom.Visible = false; cellCert.AddParagraph(_CertBannerText.ToString()); // Add a row with a single cell for the second line rowCert = tableCert.AddRow(); cellCert = rowCert.Cells[0]; cellCert.Format.Font.Color = Colors.Black; cellCert.Format.Alignment = ParagraphAlignment.Center; cellCert.Format.Font.ApplyFont(fontCert); cellCert.Borders.Left.Visible = false; cellCert.Borders.Right.Visible = false; cellCert.Borders.Top.Visible = false; cellCert.AddParagraph(CertAmountWords.ToString()); // 3RD LINE // Add a row with a single cell for the third line rowCert = tableCert.AddRow(); cellCert = rowCert.Cells[0]; Font fontCertDetails = new Font("Times New Roman", 20); cellCert.Format.Font.Color = Colors.Black; cellCert.Format.Alignment = ParagraphAlignment.Left; cellCert.Format.Font.ApplyFont(fontCertDetails); cellCert.Borders.Left.Visible = false; cellCert.Borders.Right.Visible = false; cellCert.Borders.Top.Visible = false; cellCert.Format.SpaceBefore = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(10.0); cellCert.Format.LeftIndent = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(15.0); cellCert.AddParagraph("Date:" + item.CreatedDate.ToShortDateString() + Environment.NewLine + "Presented to: " + item.ToName.ToString() + Environment.NewLine + "From: " + item.FromName.ToString() + Environment.NewLine + "Amount: " + CertAmountNumber.ToString()); //////////////////////////////// // 4th LINE // Add a row with a single cell for the forth line rowCert = tableCert.AddRow(); cellCert = rowCert.Cells[0]; Font fontCertSignature = new Font("Arial", 12); cellCert.Format.Font.Color = Colors.Black; cellCert.Format.Alignment = ParagraphAlignment.Left; cellCert.Format.Font.ApplyFont(fontCertSignature); cellCert.Borders.Left.Visible = false; cellCert.Borders.Right.Visible = false; cellCert.Borders.Top.Visible = false; cellCert.Format.SpaceBefore = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(10.0); cellCert.Format.LeftIndent = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(15.0); cellCert.AddParagraph("Authorized Signature: __________________________________________________"); //////////////////////////////// // 5th LINE // Add a row with a single cell for the fifth line rowCert = tableCert.AddRow(); cellCert = rowCert.Cells[0]; Font fontCertInvoiceNumber = new Font("Arial", 10); cellCert.Format.Font.Color = Colors.Black; cellCert.Format.Alignment = ParagraphAlignment.Center; cellCert.Format.Font.ApplyFont(fontCertInvoiceNumber); cellCert.Borders.Left.Visible = false; cellCert.Borders.Right.Visible = false; cellCert.Borders.Top.Visible = false; // cellCert.Format.AddTabStop("16cm", TabAlignment.Right); cellCert.Format.SpaceBefore = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(3.0); //cellCert.Format.LeftIndent = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(15.0); cellCert.AddParagraph("Certificate Number 00" + item.ItemId.ToString()); document.LastSection.Add(tableCert); if (item.Notes.ToString().Trim().Length > 0) { //+++++++++ ADD PARAGRAPH FOR BUYER NOTES MigraDoc.DocumentObjectModel.Paragraph paragraphFooter = section.AddParagraph(); paragraphFooter.Format.LineSpacingRule = MigraDoc.DocumentObjectModel.LineSpacingRule.Exactly; paragraphFooter.Format.LineSpacing = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(8.0); paragraphFooter.Format.SpaceBefore = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(10.0); paragraphFooter.AddText("NOTES:" + Environment.NewLine + _CertNotes.ToString()); } Paragraph footerText = new Paragraph(); footerText.Format.Alignment = ParagraphAlignment.Center; footerText.AddText(_CertFooterText.ToString()); section.Footers.Primary.Add(footerText); // Create a renderer PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(); // Associate the MigraDoc document with a renderer pdfRenderer.Document = document; // Layout and render document to PDF pdfRenderer.RenderDocument(); string pdfFilename = PortalSettings.HomeDirectoryMapPath + _PdfFilesFolder.ToString() + "Cert" + itemId.ToString() + ".pdf"; if (File.Exists(pdfFilename)) { File.Delete(pdfFilename); } pdfRenderer.PdfDocument.Save(pdfFilename); bool watermarkIsNeeded = false; if (_CertWatermark.ToString().Trim().Length > 1) { watermarkIsNeeded = true; } if (watermarkIsNeeded) { PdfDocument pdfIn = PdfReader.Open(pdfFilename, PdfDocumentOpenMode.Import); PdfDocument pdfOut = new PdfDocument(); for (int i = 0; i < pdfIn.PageCount; i++) { PdfPage pg = pdfIn.Pages[i]; pg = pdfOut.AddPage(pg); // WATERMARK TEXT string draftFlagStr = _CertWatermark.ToString(); // Get an XGraphics object for drawing beneath the existing content XGraphics gfx = XGraphics.FromPdfPage(pg, XGraphicsPdfPageOptions.Prepend); // Get the size (in point) of the text XFont fontWM = new XFont("Verdana", 62, XFontStyle.Bold); XSize size = gfx.MeasureString(draftFlagStr, fontWM); // Define a rotation transformation at the center of the page gfx.TranslateTransform(pg.Width / 2, pg.Height / 2); gfx.RotateTransform(-Math.Atan(pg.Height / pg.Width) * 180 / Math.PI); gfx.TranslateTransform(-pg.Width / 2, -pg.Height / 2); // Create a string format XStringFormat format = new XStringFormat(); format.Alignment = XStringAlignment.Near; format.LineAlignment = XLineAlignment.Near; // Create a dimmed red brush XBrush brush = new XSolidBrush(XColor.FromArgb(32, 0, 0, 255)); // Draw the string gfx.DrawString(draftFlagStr, fontWM, brush, new XPoint((pg.Width - size.Width) / 2, (pg.Height - size.Height) / 2), format); } pdfOut.Save(pdfFilename); } // Save and show the document // pdfRenderer.PdfDocument.Save("TestDocument.pdf"); Process.Start("explorer.exe", pdfFilename); HyperLinkPDF.Visible = true; HyperLinkPDF.NavigateUrl = PortalSettings.HomeDirectory + _PdfFilesFolder.ToString() + "Cert" + itemId.ToString() + ".pdf"; } catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); } }
private void Page1(PdfDocument document, int pageNum) { PdfPage page = document.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(page); // Unicode hack gfx.MUH = PdfFontEncoding.Unicode; // Get the A4 page size Unit width, height; PageSetup.GetPageSize(PageFormat.A4, out width, out height); XFont font = new XFont("Verdana", 13, XFontStyle.Bold); // You always need a MigraDoc document for rendering. Document doc = new Document(); // Add a section to the document and configure it such // that it will be in the center of the page Section section = doc.AddSection(); section.PageSetup.PageHeight = height; section.PageSetup.PageWidth = width; section.PageSetup.LeftMargin = 0; section.PageSetup.RightMargin = 0; section.PageSetup.TopMargin = 20; // Add a top paragraph with date Paragraph para = section.AddParagraph(); para.Format.Alignment = ParagraphAlignment.Right; para.Format.Font.Name = "Times New Roman"; para.Format.Font.Size = 12; para.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.DarkGray; para.AddFormattedText(dateTimePicker1.Value.Date.ToString("dddd, d MMMM yyyy"), TextFormat.Bold); // Add a bottom paragraph with page number Paragraph pg = section.AddParagraph(); pg.Format.Alignment = ParagraphAlignment.Right; pg.Format.Font.Name = "Times New Roman"; pg.Format.Font.Size = 12; pg.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.DarkGray; pg.AddFormattedText("Page " + pageNum, TextFormat.Bold); // Create a table Table table = new Table(); table.Borders.Visible = true; table.Borders.Width = 1; // Default to show borders 1 pixel wide Column table.TopPadding = 5; table.BottomPadding = 5; Column column = table.AddColumn(40); column.Format.Alignment = ParagraphAlignment.Left; column = table.AddColumn(150); column.Format.Alignment = ParagraphAlignment.Left; column = table.AddColumn(120); column.Format.Alignment = ParagraphAlignment.Center; column = table.AddColumn(120); column.Format.Alignment = ParagraphAlignment.Center; column = table.AddColumn(80); column.Format.Alignment = ParagraphAlignment.Center; table.Rows.Height = 20; Row row = table.AddRow(); row.Shading.Color = Colors.PaleGoldenrod; row.VerticalAlignment = VerticalAlignment.Top; // Table header row.Cells[0].AddParagraph("#"); row.Cells[1].AddParagraph("Name"); row.Cells[2].AddParagraph("Start"); row.Cells[3].AddParagraph("End"); row.Cells[4].AddParagraph("Duration"); // Define the last row number on the current page int lastNum; if (rowNum >= pageNum * rowsPerPage) { lastNum = pageNum * rowsPerPage; } else { lastNum = rowNum; } // Put the rows into the table for (int i = 1 + (pageNum - 1) * rowsPerPage; i <= lastNum; i++) { DataRow dr = dt.Rows[i - 1]; row = table.AddRow(); row.Cells[0].AddParagraph(i.ToString()); row.Cells[1].AddParagraph(dr["name"].ToString()); row.Cells[2].AddParagraph(dr["start"].ToString()); row.Cells[3].AddParagraph(dr["end"].ToString()); row.Cells[4].AddParagraph(dr["duration"].ToString()); } table.SetEdge(0, 0, 5, 1, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1.5, Colors.Black); doc.LastSection.Add(table); // Create a renderer and prepare (=layout) the document MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc); docRenderer.PrepareDocument(); // Render the paragraph. You can render tables or shapes the same way. docRenderer.RenderObject(gfx, XUnit.FromCentimeter(10), XUnit.FromCentimeter(1), "10cm", para); docRenderer.RenderObject(gfx, XUnit.FromCentimeter(2), XUnit.FromCentimeter(2), "12cm", table); docRenderer.RenderObject(gfx, XUnit.FromCentimeter(10), XUnit.FromCentimeter(28), "10cm", pg); }
/// <summary> /// Created PDF document from given content. See https://github.com/CommunityHiQ/Frends.Community.PDFWriter /// </summary> /// <param name="outputFile"></param> /// <param name="documentSettings"></param> /// <param name="content"></param> /// <param name="options"></param> /// <returns>Object { bool Success, string FileName }</returns> public static Output CreatePdf([PropertyTab] FileProperties outputFile, [PropertyTab] DocumentSettings documentSettings, [PropertyTab] DocumentContent content, [PropertyTab] Options options) { try { var document = new Document(); if (!string.IsNullOrWhiteSpace(documentSettings.Title)) { document.Info.Title = documentSettings.Title; } if (!string.IsNullOrWhiteSpace(documentSettings.Author)) { document.Info.Author = documentSettings.Author; } // Get the selected page size Unit width, height; PageSetup.GetPageSize(documentSettings.Size.ConvertEnum <PageFormat>(), out width, out height); var section = document.AddSection(); SetupPage(section.PageSetup, width, height, documentSettings); // index for stylename var elementNumber = 0; // add page elements foreach (var pageElement in content.Contents) { var styleName = $"style_{elementNumber}"; var style = document.Styles.AddStyle(styleName, "Normal"); switch (pageElement.ContentType) { case ElementType.Image: AddImage(section, pageElement, width, style); break; case ElementType.PageBreak: section = document.AddSection(); SetupPage(section.PageSetup, width, height, documentSettings); break; case ElementType.Header: SetFont(style, pageElement); SetParagraphStyle(style, pageElement); AddHeaderFooterContent(section, pageElement, style, true); break; case ElementType.Footer: SetFont(style, pageElement); SetParagraphStyle(style, pageElement); AddHeaderFooterContent(section, pageElement, style, false); break; case ElementType.Table: AddTable(section, pageElement, width); break; default: SetFont(style, pageElement); SetParagraphStyle(style, pageElement); AddTextContent(section, pageElement, style); break; } elementNumber++; } string fileName = Path.Combine(outputFile.Directory, outputFile.FileName); int fileNameIndex = 1; while (File.Exists(fileName) && outputFile.FileExistsAction != FileExistsActionEnum.Overwrite) { switch (outputFile.FileExistsAction) { case FileExistsActionEnum.Error: throw new Exception($"File {fileName} already exists."); case FileExistsActionEnum.Rename: fileName = Path.Combine(outputFile.Directory, $"{Path.GetFileNameWithoutExtension(outputFile.FileName)}_({fileNameIndex}){Path.GetExtension(outputFile.FileName)}"); break; } fileNameIndex++; } // save document var pdfRenderer = new PdfDocumentRenderer(outputFile.Unicode) { Document = document }; pdfRenderer.RenderDocument(); if (!options.UseGivenCredentials) { pdfRenderer.PdfDocument.Save(fileName); } else { var domainAndUserName = GetDomainAndUserName(options.UserName); Impersonation.RunAsUser(new UserCredentials(domainAndUserName[0], domainAndUserName[1], options.Password), LogonType.NewCredentials, () => pdfRenderer.PdfDocument.Save(fileName)); } return(new Output { Success = true, FileName = fileName }); } catch (Exception ex) { if (options.ThrowErrorOnFailure) { throw ex; } return(new Output { Success = false }); } }