Export PDF Document to images
The sample demonstrates how to export PDF pages as images by PdfDocumentViewer Component.
using System; using System.Drawing; using System.IO; using System.Windows.Forms; using Spire.PdfViewer.Forms; namespace Spire.PdfView.Demos.Export { class Program { private static PdfDocumentViewer viewer = null; [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); viewer = new PdfDocumentViewer(); viewer.LoadFromFile("PDFViewer.pdf"); //form and child components Form mainForm = new Form(); mainForm.Text = "Spire.PdfView Demo - Export"; mainForm.Size = new System.Drawing.Size(800, 600); mainForm.StartPosition = FormStartPosition.CenterScreen; TableLayoutPanel table = new TableLayoutPanel(); table.ColumnCount = 3; table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); table.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 20)); table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); table.RowCount = 2; table.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); table.RowStyles.Add(new RowStyle(SizeType.Absolute, 30)); table.Controls.Add(viewer, 0, 0); table.SetColumnSpan(viewer, 3); viewer.Dock = DockStyle.Fill; //Export current page to one image Button button = new Button(); button.Text = "Export to one image"; button.Size = new Size(180, 24); button.TextAlign = ContentAlignment.MiddleCenter; table.Controls.Add(button, 0, 1); button.Dock = DockStyle.Right; button.Click += ExportToOneImage; //Export current pdf document to multiple images button = new Button(); button.Text = "Export to multiple images"; button.Size = new Size(180, 24); button.TextAlign = ContentAlignment.MiddleCenter; table.Controls.Add(button, 2, 1); button.Dock = DockStyle.Left; button.Click += ExportToMultipleImages; mainForm.Controls.Add(table); table.Dock = DockStyle.Fill; Application.Run(mainForm); } private static void ExportToOneImage(object sender, EventArgs e) { if (viewer.PageCount > 0) { SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "PNG Format(*.png)|*.png"; if (dialog.ShowDialog() == DialogResult.OK) { int currentPage = viewer.CurrentPageNumber; Bitmap image = viewer.SaveAsImage(currentPage - 1); image.Save(dialog.FileName); } } } private static void ExportToMultipleImages(object sender, EventArgs e) { if (viewer.PageCount > 0) { FolderBrowserDialog dialog = new FolderBrowserDialog(); if (dialog.ShowDialog() == DialogResult.OK) { int currentPage = viewer.CurrentPageNumber; Bitmap[] images = viewer.SaveAsImage(0, currentPage - 1); for (int i = 0; i < images.Length; i++) { String fileName = Path.Combine(dialog.SelectedPath, String.Format("PDFViewer-{0}.png", i)); images[i].Save(fileName); } } } } } }
Imports System.Drawing Imports System.IO Imports System.Windows.Forms Imports Spire.PdfViewer.Forms Namespace Spire.PdfView.Demos.Export Friend NotInheritable Class Program Private Shared viewer As PdfDocumentViewer = Nothing _ Shared Sub Main() Application.EnableVisualStyles() Application.SetCompatibleTextRenderingDefault(False) viewer = New PdfDocumentViewer() viewer.LoadFromFile("PDFViewer.pdf") 'form and child components Dim mainForm As New Form() mainForm.Text = "Spire.PdfView Demo - Export" mainForm.Size = New System.Drawing.Size(800, 600) mainForm.StartPosition = FormStartPosition.CenterScreen Dim table As New TableLayoutPanel() table.ColumnCount = 3 table.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 50)) table.ColumnStyles.Add(New ColumnStyle(SizeType.Absolute, 20)) table.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 50)) table.RowCount = 2 table.RowStyles.Add(New RowStyle(SizeType.Percent, 100)) table.RowStyles.Add(New RowStyle(SizeType.Absolute, 30)) table.Controls.Add(viewer, 0, 0) table.SetColumnSpan(viewer, 3) viewer.Dock = DockStyle.Fill 'Export current page to one image Dim button As New Button() button.Text = "Export to one image" button.Size = New Size(180, 24) button.TextAlign = ContentAlignment.MiddleCenter table.Controls.Add(button, 0, 1) button.Dock = DockStyle.Right AddHandler button.Click, AddressOf ExportToOneImage 'Export current pdf document to multiple images button = New Button() button.Text = "Export to multiple images" button.Size = New Size(180, 24) button.TextAlign = ContentAlignment.MiddleCenter table.Controls.Add(button, 2, 1) button.Dock = DockStyle.Left AddHandler button.Click, AddressOf ExportToMultipleImages mainForm.Controls.Add(table) table.Dock = DockStyle.Fill Application.Run(mainForm) End Sub Private Shared Sub ExportToOneImage(ByVal sender As Object, ByVal e As EventArgs) If viewer.PageCount > 0 Then Dim dialog As New SaveFileDialog() dialog.Filter = "PNG Format(*.png)|*.png" If dialog.ShowDialog() = DialogResult.OK Then Dim currentPage As Integer = viewer.CurrentPageNumber Dim image As Bitmap = viewer.SaveAsImage(currentPage - 1) image.Save(dialog.FileName) End If End If End Sub Private Shared Sub ExportToMultipleImages(ByVal sender As Object, ByVal e As EventArgs) If viewer.PageCount > 0 Then Dim dialog As New FolderBrowserDialog() If dialog.ShowDialog() = DialogResult.OK Then Dim currentPage As Integer = viewer.CurrentPageNumber Dim images As Bitmap() = viewer.SaveAsImage(0, currentPage - 1) For i As Integer = 0 To images.Length - 1 Dim fileName As [String] = Path.Combine(dialog.SelectedPath, [String].Format("PDFViewer-{0}.png", i)) images(i).Save(fileName) Next End If End If End Sub End Class End Namespace
PDF Extract in C#, VB.NET
The sample demonstrates how to extract images and text from PDF document.
(NO screenshot)
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Text; using Spire.Pdf; namespace Extraction { class Program { static void Main(string[] args) { //Create a pdf document. PdfDocument doc = new PdfDocument(); doc.LoadFromFile(@"Sample2.pdf"); StringBuilder buffer = new StringBuilder(); IList<Image> images = new List<Image>(); foreach (PdfPageBase page in doc.Pages) { buffer.Append(page.ExtractText()); foreach (Image image in page.ExtractImages()) { images.Add(image); } } doc.Close(); //save text String fileName = "TextInPdf.txt"; File.WriteAllText(fileName, buffer.ToString()); //save image int index = 0; foreach (Image image in images) { String imageFileName = String.Format("Image-{0}.png", index++); image.Save(imageFileName, ImageFormat.Png); } //Launching the Text file. System.Diagnostics.Process.Start(fileName); } } }
Imports System.Collections.Generic Imports System.Drawing Imports System.Drawing.Imaging Imports System.IO Imports System.Text Imports Spire.Pdf Namespace Extraction Friend Class Program Shared Sub Main(ByVal args() As String) 'Create a pdf document. Dim doc As New PdfDocument() doc.LoadFromFile("Sample2.pdf") Dim buffer As New StringBuilder() Dim images As IList(Of Image) = New List(Of Image)() For Each page As PdfPageBase In doc.Pages buffer.Append(page.ExtractText()) For Each image As Image In page.ExtractImages() images.Add(image) Next image Next page doc.Close() 'save text Dim fileName As String = "TextInPdf.txt" File.WriteAllText(fileName, buffer.ToString()) 'save image Dim index As Integer = 0 For Each image As Image In images Dim imageFileName As String = String.Format("Image-{0}.png", index) index += 1 image.Save(imageFileName, ImageFormat.Png) Next image 'Launching the Text file. Process.Start(fileName) End Sub End Class End Namespace
PDF ImageWaterMark in C#, VB.NET
The sample demonstrates how to draw an image as watermark in PDF document.
using System; using System.Drawing; using Spire.Pdf; using Spire.Pdf.Graphics; namespace ImageWaterMark { class Program { static void Main(string[] args) { //Create a pdf document. PdfDocument doc = new PdfDocument(); //margin PdfUnitConvertor unitCvtr = new PdfUnitConvertor(); PdfMargins margin = new PdfMargins(); margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point); margin.Bottom = margin.Top; margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point); margin.Right = margin.Left; // Create one page PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin); Image img = Image.FromFile(@"Background.png"); page.BackgroundImage = img; //Draw page DrawPage(page); //Save pdf file. doc.SaveToFile("ImageWaterMark.pdf"); doc.Close(); //Launching the Pdf file. System.Diagnostics.Process.Start("ImageWaterMark.pdf"); } private static void DrawPage(PdfPageBase page) { float pageWidth = page.Canvas.ClientSize.Width; float y = 0; //page header PdfPen pen1 = new PdfPen(Color.LightGray, 1f); PdfBrush brush1 = new PdfSolidBrush(Color.LightGray); PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 8f, FontStyle.Italic)); PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Right); String text = "Demo of Spire.Pdf"; page.Canvas.DrawString(text, font1, brush1, pageWidth, y, format1); SizeF size = font1.MeasureString(text, format1); y = y + size.Height + 1; page.Canvas.DrawLine(pen1, 0, y, pageWidth, y); //title y = y + 5; PdfBrush brush2 = new PdfSolidBrush(Color.Black); PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold)); PdfStringFormat format2 = new PdfStringFormat(PdfTextAlignment.Center); format2.CharacterSpacing = 1f; text = "Summary of Science"; page.Canvas.DrawString(text, font2, brush2, pageWidth / 2, y, format2); size = font2.MeasureString(text, format2); y = y + size.Height + 6; //icon PdfImage image = PdfImage.FromFile(@"Wikipedia_Science.png"); page.Canvas.DrawImage(image, new PointF(pageWidth - image.PhysicalDimension.Width, y)); float imageLeftSpace = pageWidth - image.PhysicalDimension.Width - 2; float imageBottom = image.PhysicalDimension.Height + y; //refenrence content PdfTrueTypeFont font3 = new PdfTrueTypeFont(new Font("Arial", 9f)); PdfStringFormat format3 = new PdfStringFormat(); format3.ParagraphIndent = font3.Size * 2; format3.MeasureTrailingSpaces = true; format3.LineSpacing = font3.Size * 1.5f; String text1 = "(All text and picture from "; String text2 = "Wikipedia"; String text3 = ", the free encyclopedia)"; page.Canvas.DrawString(text1, font3, brush2, 0, y, format3); size = font3.MeasureString(text1, format3); float x1 = size.Width; format3.ParagraphIndent = 0; PdfTrueTypeFont font4 = new PdfTrueTypeFont(new Font("Arial", 9f, FontStyle.Underline)); PdfBrush brush3 = PdfBrushes.Blue; page.Canvas.DrawString(text2, font4, brush3, x1, y, format3); size = font4.MeasureString(text2, format3); x1 = x1 + size.Width; page.Canvas.DrawString(text3, font3, brush2, x1, y, format3); y = y + size.Height; //content PdfStringFormat format4 = new PdfStringFormat(); text = System.IO.File.ReadAllText(@"Summary_of_Science.txt"); PdfTrueTypeFont font5 = new PdfTrueTypeFont(new Font("Arial", 10f)); format4.LineSpacing = font5.Size * 1.5f; PdfStringLayouter textLayouter = new PdfStringLayouter(); float imageLeftBlockHeight = imageBottom - y; PdfStringLayoutResult result = textLayouter.Layout(text, font5, format4, new SizeF(imageLeftSpace, imageLeftBlockHeight)); if (result.ActualSize.Height < imageBottom - y) { imageLeftBlockHeight = imageLeftBlockHeight + result.LineHeight; result = textLayouter.Layout(text, font5, format4, new SizeF(imageLeftSpace, imageLeftBlockHeight)); } foreach (LineInfo line in result.Lines) { page.Canvas.DrawString(line.Text, font5, brush2, 0, y, format4); y = y + result.LineHeight; } PdfTextWidget textWidget = new PdfTextWidget(result.Remainder, font5, brush2); PdfTextLayout textLayout = new PdfTextLayout(); textLayout.Break = PdfLayoutBreakType.FitPage; textLayout.Layout = PdfLayoutType.Paginate; RectangleF bounds = new RectangleF(new PointF(0, y), page.Canvas.ClientSize); textWidget.StringFormat = format4; textWidget.Draw(page, bounds, textLayout); } } }
Imports System.Drawing Imports Spire.Pdf Imports Spire.Pdf.Graphics Namespace ImageWaterMark Friend Class Program Shared Sub Main(ByVal args() As String) 'Create a pdf document. Dim doc As New PdfDocument() 'margin Dim unitCvtr As New PdfUnitConvertor() Dim margin As New PdfMargins() margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point) margin.Bottom = margin.Top margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point) margin.Right = margin.Left ' Create one page Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, margin) Dim img As Image = Image.FromFile("Background.png") page.BackgroundImage = img 'Draw table DrawPage(page) 'Save pdf file. doc.SaveToFile("ImageWaterMark.pdf") doc.Close() 'Launching the Pdf file. Process.Start("ImageWaterMark.pdf") End Sub Private Shared Sub DrawPage(ByVal page As PdfPageBase) Dim pageWidth As Single = page.Canvas.ClientSize.Width Dim y As Single = 0 'page header Dim pen1 As New PdfPen(Color.LightGray, 1.0F) Dim brush1 As PdfBrush = New PdfSolidBrush(Color.LightGray) Dim font1 As New PdfTrueTypeFont(New Font("Arial", 8.0F, FontStyle.Italic)) Dim format1 As New PdfStringFormat(PdfTextAlignment.Right) Dim text As String = "Demo of Spire.Pdf" page.Canvas.DrawString(text, font1, brush1, pageWidth, y, format1) Dim size As SizeF = font1.MeasureString(text, format1) y = y + size.Height + 1 page.Canvas.DrawLine(pen1, 0, y, pageWidth, y) 'title y = y + 5 Dim brush2 As PdfBrush = New PdfSolidBrush(Color.Black) Dim font2 As New PdfTrueTypeFont(New Font("Arial", 16.0F, FontStyle.Bold)) Dim format2 As New PdfStringFormat(PdfTextAlignment.Center) format2.CharacterSpacing = 1.0F text = "Summary of Science" page.Canvas.DrawString(text, font2, brush2, pageWidth / 2, y, format2) size = font2.MeasureString(text, format2) y = y + size.Height + 6 'icon Dim image As PdfImage = PdfImage.FromFile("Wikipedia_Science.png") page.Canvas.DrawImage(image, New PointF(pageWidth - image.PhysicalDimension.Width, y)) Dim imageLeftSpace As Single = pageWidth - image.PhysicalDimension.Width - 2 Dim imageBottom As Single = image.PhysicalDimension.Height + y 'refenrence content Dim font3 As New PdfTrueTypeFont(New Font("Arial", 9.0F)) Dim format3 As New PdfStringFormat() format3.ParagraphIndent = font3.Size * 2 format3.MeasureTrailingSpaces = True format3.LineSpacing = font3.Size * 1.5F Dim text1 As String = "(All text and picture from " Dim text2 As String = "Wikipedia" Dim text3 As String = ", the free encyclopedia)" page.Canvas.DrawString(text1, font3, brush2, 0, y, format3) size = font3.MeasureString(text1, format3) Dim x1 As Single = size.Width format3.ParagraphIndent = 0 Dim font4 As New PdfTrueTypeFont(New Font("Arial", 9.0F, FontStyle.Underline)) Dim brush3 As PdfBrush = PdfBrushes.Blue page.Canvas.DrawString(text2, font4, brush3, x1, y, format3) size = font4.MeasureString(text2, format3) x1 = x1 + size.Width page.Canvas.DrawString(text3, font3, brush2, x1, y, format3) y = y + size.Height 'content Dim format4 As New PdfStringFormat() text = System.IO.File.ReadAllText("Summary_of_Science.txt") Dim font5 As New PdfTrueTypeFont(New Font("Arial", 10.0F)) format4.LineSpacing = font5.Size * 1.5F Dim textLayouter As New PdfStringLayouter() Dim imageLeftBlockHeight As Single = imageBottom - y Dim result As PdfStringLayoutResult _ = textLayouter.Layout(text, font5, format4, New SizeF(imageLeftSpace, imageLeftBlockHeight)) If result.ActualSize.Height < imageBottom - y Then imageLeftBlockHeight = imageLeftBlockHeight + result.LineHeight result = textLayouter.Layout(text, font5, format4, New SizeF(imageLeftSpace, imageLeftBlockHeight)) End If For Each line As LineInfo In result.Lines page.Canvas.DrawString(line.Text, font5, brush2, 0, y, format4) y = y + result.LineHeight Next line Dim textWidget As New PdfTextWidget(result.Remainder, font5, brush2) Dim textLayout As New PdfTextLayout() textLayout.Break = PdfLayoutBreakType.FitPage textLayout.Layout = PdfLayoutType.Paginate Dim bounds As New RectangleF(New PointF(0, y), page.Canvas.ClientSize) textWidget.StringFormat = format4 textWidget.Draw(page, bounds, textLayout) End Sub End Class End Namespace
PDF ImageTable in C#, VB.NET
The sample demonstrates how to export data and pictures from database into a table in PDF document and set table format.
using System; using System.Data; using System.Data.OleDb; using System.Drawing; using System.IO; using Spire.Pdf; using Spire.Pdf.Graphics; using Spire.Pdf.Tables; namespace ImageTable { class Program { static void Main(string[] args) { //Create a pdf document. PdfDocument doc = new PdfDocument(); //margin PdfUnitConvertor unitCvtr = new PdfUnitConvertor(); PdfMargins margin = new PdfMargins(); margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point); margin.Bottom = margin.Top; margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point); margin.Right = margin.Left; // Create one page PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin); float y = 10; //title PdfBrush brush1 = PdfBrushes.Black; PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold)); PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center); page.Canvas.DrawString("Country List", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1); y = y + font1.MeasureString("Country List", format1).Height; y = y + 5; //create data table PdfTable table = new PdfTable(); table.Style.CellPadding = 2; table.Style.BorderPen = new PdfPen(brush1, 0.75f); table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.SkyBlue; table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("Arial", 10f)); table.Style.AlternateStyle = new PdfCellStyle(); table.Style.AlternateStyle.BackgroundBrush = PdfBrushes.LightYellow; table.Style.AlternateStyle.Font = new PdfTrueTypeFont(new Font("Arial", 10f)); table.Style.HeaderSource = PdfHeaderSource.ColumnCaptions; table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue; table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("Arial", 11f, FontStyle.Bold)); table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center); table.Style.ShowHeader = true; using (OleDbConnection conn = new OleDbConnection()) { conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=demo.mdb"; OleDbCommand command = new OleDbCommand(); command.CommandText = " select Name, '' as Flag, Capital, Continent, Area, Population, Flag as FlagData from country "; command.Connection = conn; using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command)) { DataTable dataTable = new DataTable(); dataAdapter.Fill(dataTable); dataTable.Columns.Add(new DataColumn("FlagImage", typeof(PdfImage))); table.DataSourceType = PdfTableDataSourceType.TableDirect; table.DataSource = dataTable; } } float width = page.Canvas.ClientSize.Width - (table.Columns.Count + 1) * table.Style.BorderPen.Width; table.Columns[0].Width = width * 0.21f; table.Columns[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle); table.Columns[1].Width = width * 0.10f; table.Columns[1].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle); table.Columns[2].Width = width * 0.19f; table.Columns[2].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle); table.Columns[3].Width = width * 0.21f; table.Columns[3].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle); table.Columns[4].Width = width * 0.12f; table.Columns[4].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle); table.Columns[5].Width = width * 0.17f; table.Columns[5].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle); table.BeginRowLayout += new BeginRowLayoutEventHandler(table_BeginRowLayout); table.EndCellLayout += new EndCellLayoutEventHandler(table_EndCellLayout); PdfTableLayoutFormat tableLayout = new PdfTableLayoutFormat(); tableLayout.Break = PdfLayoutBreakType.FitElement; tableLayout.Layout = PdfLayoutType.Paginate; tableLayout.EndColumnIndex = table.Columns.Count - 2 - 1; PdfLayoutResult result = table.Draw(page, new PointF(0, y), tableLayout); y = y + result.Bounds.Height + 5; PdfBrush brush2 = PdfBrushes.Gray; PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 9f)); page.Canvas.DrawString(String.Format("* {0} countries in the list.", table.Rows.Count), font2, brush2, 5, y); //Save pdf file. doc.SaveToFile("ImageTable.pdf"); doc.Close(); //Launching the Pdf file. System.Diagnostics.Process.Start("ImageTable.pdf"); } static void table_EndCellLayout(object sender, EndCellLayoutEventArgs args) { if (args.RowIndex < 0) { //header return; } if (args.CellIndex == 1) { DataTable dataTable = (sender as PdfTable).DataSource as DataTable; PdfImage image = dataTable.Rows[args.RowIndex][7] as PdfImage; float x = (args.Bounds.Width - image.PhysicalDimension.Width) / 2 + args.Bounds.X; float y = (args.Bounds.Height - image.PhysicalDimension.Height) / 2 + args.Bounds.Y; args.Graphics.DrawImage(image, x, y); } } static void table_BeginRowLayout(object sender, BeginRowLayoutEventArgs args) { if (args.RowIndex < 0) { //header return; } DataTable dataTable = (sender as PdfTable).DataSource as DataTable; byte[] imageData = dataTable.Rows[args.RowIndex][6] as byte[]; using (MemoryStream stream = new MemoryStream(imageData)) { PdfImage image = PdfImage.FromStream(stream); args.MinimalHeight = 4 + image.PhysicalDimension.Height; dataTable.Rows[args.RowIndex][7] = image; } } } }
Imports System.Data Imports System.Data.OleDb Imports System.Drawing Imports System.IO Imports Spire.Pdf Imports Spire.Pdf.Graphics Imports Spire.Pdf.Tables Namespace ImageTable Friend Class Program Shared Sub Main(ByVal args() As String) 'Create a pdf document. Dim doc As New PdfDocument() 'margin Dim unitCvtr As New PdfUnitConvertor() Dim margin As New PdfMargins() margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point) margin.Bottom = margin.Top margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point) margin.Right = margin.Left ' Create one page Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, margin) Dim y As Single = 10 'title Dim brush1 As PdfBrush = PdfBrushes.Black Dim font1 As New PdfTrueTypeFont(New Font("Arial", 16.0F, FontStyle.Bold)) Dim format1 As New PdfStringFormat(PdfTextAlignment.Center) page.Canvas.DrawString("Country List", font1, brush1, page.Canvas.ClientSize.Width \ 2, y, format1) y = y + font1.MeasureString("Country List", format1).Height y = y + 5 'create data table Dim table As New PdfTable() table.Style.CellPadding = 2 table.Style.BorderPen = New PdfPen(brush1, 0.75F) table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.SkyBlue table.Style.DefaultStyle.Font = New PdfTrueTypeFont(New Font("Arial", 10.0F)) table.Style.AlternateStyle = New PdfCellStyle() table.Style.AlternateStyle.BackgroundBrush = PdfBrushes.LightYellow table.Style.AlternateStyle.Font = New PdfTrueTypeFont(New Font("Arial", 10.0F)) table.Style.HeaderSource = PdfHeaderSource.ColumnCaptions table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue table.Style.HeaderStyle.Font = New PdfTrueTypeFont(New Font("Arial", 11.0F, FontStyle.Bold)) table.Style.HeaderStyle.StringFormat = New PdfStringFormat(PdfTextAlignment.Center) table.Style.ShowHeader = True Using conn As New OleDbConnection() conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=demo.mdb" Dim command As New OleDbCommand() command.CommandText _ = " select Name, '' as Flag, Capital, Continent, Area, Population, Flag as FlagData from country " command.Connection = conn Using dataAdapter As New OleDbDataAdapter(command) Dim dataTable As New DataTable() dataAdapter.Fill(dataTable) dataTable.Columns.Add(New DataColumn("FlagImage", GetType(PdfImage))) table.DataSourceType = PdfTableDataSourceType.TableDirect table.DataSource = dataTable End Using End Using Dim width As Single = page.Canvas.ClientSize.Width - (table.Columns.Count + 1) * table.Style.BorderPen.Width table.Columns(0).Width = width * 0.21F table.Columns(0).StringFormat = New PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle) table.Columns(1).Width = width * 0.1F table.Columns(1).StringFormat = New PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle) table.Columns(2).Width = width * 0.19F table.Columns(2).StringFormat = New PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle) table.Columns(3).Width = width * 0.21F table.Columns(3).StringFormat = New PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle) table.Columns(4).Width = width * 0.12F table.Columns(4).StringFormat = New PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle) table.Columns(5).Width = width * 0.17F table.Columns(5).StringFormat = New PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle) AddHandler table.BeginRowLayout, AddressOf table_BeginRowLayout AddHandler table.EndCellLayout, AddressOf table_EndCellLayout Dim tableLayout As New PdfTableLayoutFormat() tableLayout.Break = PdfLayoutBreakType.FitElement tableLayout.Layout = PdfLayoutType.Paginate tableLayout.EndColumnIndex = table.Columns.Count - 2 - 1 Dim result As PdfLayoutResult = table.Draw(page, New PointF(0, y), tableLayout) y = y + result.Bounds.Height + 5 Dim brush2 As PdfBrush = PdfBrushes.Gray Dim font2 As New PdfTrueTypeFont(New Font("Arial", 9.0F)) page.Canvas.DrawString(String.Format("* {0} countries in the list.", table.Rows.Count), font2, brush2, 5, y) 'Save pdf file. doc.SaveToFile("ImageTable.pdf") doc.Close() 'Launching the Pdf file. Process.Start("ImageTable.pdf") End Sub Private Shared Sub table_EndCellLayout(ByVal sender As Object, ByVal args As EndCellLayoutEventArgs) If args.RowIndex < 0 Then 'header Return End If If args.CellIndex = 1 Then Dim dataTable As DataTable = TryCast((TryCast(sender, PdfTable)).DataSource, DataTable) Dim image As PdfImage = TryCast(dataTable.Rows(args.RowIndex)(7), PdfImage) Dim x As Single = (args.Bounds.Width - image.PhysicalDimension.Width) / 2 + args.Bounds.X Dim y As Single = (args.Bounds.Height - image.PhysicalDimension.Height) / 2 + args.Bounds.Y args.Graphics.DrawImage(image, x, y) End If End Sub Private Shared Sub table_BeginRowLayout(ByVal sender As Object, ByVal args As BeginRowLayoutEventArgs) If args.RowIndex < 0 Then 'header Return End If Dim dataTable As DataTable = TryCast((TryCast(sender, PdfTable)).DataSource, DataTable) Dim imageData() As Byte = TryCast(dataTable.Rows(args.RowIndex)(6), Byte()) Using stream As New MemoryStream(imageData) Dim image As PdfImage = PdfImage.FromStream(stream) args.MinimalHeight = 4 + image.PhysicalDimension.Height dataTable.Rows(args.RowIndex)(7) = image End Using End Sub End Class End Namespace
PDF Template in C#, VB.NET
The sample demonstrates how to set PDF documentaion template, page header&footer, page number and automatic page number count.
using System; using System.Drawing; using Spire.Pdf; using Spire.Pdf.AutomaticFields; using Spire.Pdf.Graphics; namespace Template { class Program { static void Main(string[] args) { //Create a pdf document. PdfDocument doc = new PdfDocument(); doc.ViewerPreferences.PageLayout = PdfPageLayout.TwoColumnLeft; //margin PdfUnitConvertor unitCvtr = new PdfUnitConvertor(); PdfMargins margin = new PdfMargins(); margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point); margin.Bottom = margin.Top; margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point); margin.Right = margin.Left; SetDocumentTemplate(doc, PdfPageSize.A4, margin); //create section PdfSection section = doc.Sections.Add(); section.PageSettings.Size = PdfPageSize.A4; section.PageSettings.Margins = new PdfMargins(0); SetSectionTemplate(section, PdfPageSize.A4, margin, "Section 1"); // Create one page PdfNewPage page = section.Pages.Add(); //Draw page DrawPage(page); page = section.Pages.Add(); DrawPage(page); page = section.Pages.Add(); DrawPage(page); page = section.Pages.Add(); DrawPage(page); page = section.Pages.Add(); DrawPage(page); //Save pdf file. doc.SaveToFile("Template.pdf"); doc.Close(); //Launching the Pdf file. System.Diagnostics.Process.Start("Template.pdf"); } private static void DrawPage(PdfNewPage page) { float pageWidth = page.Canvas.ClientSize.Width; float y = 0; //title y = y + 5; PdfBrush brush2 = new PdfSolidBrush(Color.Black); PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold)); PdfStringFormat format2 = new PdfStringFormat(PdfTextAlignment.Center); format2.CharacterSpacing = 1f; String text = "Summary of Science"; page.Canvas.DrawString(text, font2, brush2, pageWidth / 2, y, format2); SizeF size = font2.MeasureString(text, format2); y = y + size.Height + 6; //icon PdfImage image = PdfImage.FromFile(@"Wikipedia_Science.png"); page.Canvas.DrawImage(image, new PointF(pageWidth - image.PhysicalDimension.Width, y)); float imageLeftSpace = pageWidth - image.PhysicalDimension.Width - 2; float imageBottom = image.PhysicalDimension.Height + y; //refenrence content PdfTrueTypeFont font3 = new PdfTrueTypeFont(new Font("Arial", 9f)); PdfStringFormat format3 = new PdfStringFormat(); format3.ParagraphIndent = font3.Size * 2; format3.MeasureTrailingSpaces = true; format3.LineSpacing = font3.Size * 1.5f; String text1 = "(All text and picture from "; String text2 = "Wikipedia"; String text3 = ", the free encyclopedia)"; page.Canvas.DrawString(text1, font3, brush2, 0, y, format3); size = font3.MeasureString(text1, format3); float x1 = size.Width; format3.ParagraphIndent = 0; PdfTrueTypeFont font4 = new PdfTrueTypeFont(new Font("Arial", 9f, FontStyle.Underline)); PdfBrush brush3 = PdfBrushes.Blue; page.Canvas.DrawString(text2, font4, brush3, x1, y, format3); size = font4.MeasureString(text2, format3); x1 = x1 + size.Width; page.Canvas.DrawString(text3, font3, brush2, x1, y, format3); y = y + size.Height; //content PdfStringFormat format4 = new PdfStringFormat(); text = System.IO.File.ReadAllText(@"Summary_of_Science.txt"); PdfTrueTypeFont font5 = new PdfTrueTypeFont(new Font("Arial", 10f)); format4.LineSpacing = font5.Size * 1.5f; PdfStringLayouter textLayouter = new PdfStringLayouter(); float imageLeftBlockHeight = imageBottom - y; PdfStringLayoutResult result = textLayouter.Layout(text, font5, format4, new SizeF(imageLeftSpace, imageLeftBlockHeight)); if (result.ActualSize.Height < imageBottom - y) { imageLeftBlockHeight = imageLeftBlockHeight + result.LineHeight; result = textLayouter.Layout(text, font5, format4, new SizeF(imageLeftSpace, imageLeftBlockHeight)); } foreach (LineInfo line in result.Lines) { page.Canvas.DrawString(line.Text, font5, brush2, 0, y, format4); y = y + result.LineHeight; } PdfTextWidget textWidget = new PdfTextWidget(result.Remainder, font5, brush2); PdfTextLayout textLayout = new PdfTextLayout(); textLayout.Break = PdfLayoutBreakType.FitPage; textLayout.Layout = PdfLayoutType.Paginate; RectangleF bounds = new RectangleF(new PointF(0, y), page.Canvas.ClientSize); textWidget.StringFormat = format4; textWidget.Draw(page, bounds, textLayout); } private static void SetSectionTemplate(PdfSection section, SizeF pageSize, PdfMargins margin, string label) { PdfPageTemplateElement leftSpace = new PdfPageTemplateElement(margin.Left, pageSize.Height); leftSpace.Foreground = true; section.Template.OddLeft = leftSpace; PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 9f, FontStyle.Italic)); PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle); float y = (pageSize.Height - margin.Top - margin.Bottom) * (1 - 0.618f); RectangleF bounds = new RectangleF(10, y, margin.Left - 20, font.Height + 6); leftSpace.Graphics.DrawRectangle(PdfBrushes.OrangeRed, bounds); leftSpace.Graphics.DrawString(label, font, PdfBrushes.White, bounds, format); PdfPageTemplateElement rightSpace = new PdfPageTemplateElement(margin.Right, pageSize.Height); rightSpace.Foreground = true; section.Template.EvenRight = rightSpace; bounds = new RectangleF(10, y, margin.Right - 20, font.Height + 6); rightSpace.Graphics.DrawRectangle(PdfBrushes.SaddleBrown, bounds); rightSpace.Graphics.DrawString(label, font, PdfBrushes.White, bounds, format); } private static void SetDocumentTemplate(PdfDocument doc, SizeF pageSize, PdfMargins margin) { PdfPageTemplateElement leftSpace = new PdfPageTemplateElement(margin.Left, pageSize.Height); doc.Template.Left = leftSpace; PdfPageTemplateElement topSpace = new PdfPageTemplateElement(pageSize.Width, margin.Top); topSpace.Foreground = true; doc.Template.Top = topSpace; //draw header label PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 9f, FontStyle.Italic)); PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Right); String label = "Demo of Spire.Pdf"; SizeF size = font.MeasureString(label, format); float y = topSpace.Height - font.Height - 1; PdfPen pen = new PdfPen(Color.Black, 0.75f); topSpace.Graphics.SetTransparency(0.5f); topSpace.Graphics.DrawLine(pen, margin.Left, y, pageSize.Width - margin.Right, y); y = y - 1 - size.Height; topSpace.Graphics.DrawString(label, font, PdfBrushes.Black, pageSize.Width - margin.Right, y, format); PdfPageTemplateElement rightSpace = new PdfPageTemplateElement(margin.Right, pageSize.Height); doc.Template.Right = rightSpace; PdfPageTemplateElement bottomSpace = new PdfPageTemplateElement(pageSize.Width, margin.Bottom); bottomSpace.Foreground = true; doc.Template.Bottom = bottomSpace; //draw footer label y = font.Height + 1; bottomSpace.Graphics.SetTransparency(0.5f); bottomSpace.Graphics.DrawLine(pen, margin.Left, y, pageSize.Width - margin.Right, y); y = y + 1; PdfPageNumberField pageNumber = new PdfPageNumberField(); PdfPageCountField pageCount = new PdfPageCountField(); PdfCompositeField pageNumberLabel = new PdfCompositeField(); pageNumberLabel.AutomaticFields = new PdfAutomaticField[] { pageNumber, pageCount }; pageNumberLabel.Brush = PdfBrushes.Black; pageNumberLabel.Font = font; pageNumberLabel.StringFormat = format; pageNumberLabel.Text = "page {0} of {1}"; pageNumberLabel.Draw(bottomSpace.Graphics, pageSize.Width - margin.Right, y); PdfImage headerImage = PdfImage.FromFile(@"Header.png"); PointF pageLeftTop = new PointF(-margin.Left, -margin.Top); PdfPageTemplateElement header = new PdfPageTemplateElement(pageLeftTop, headerImage.PhysicalDimension); header.Foreground = false; header.Graphics.SetTransparency(0.5f); header.Graphics.DrawImage(headerImage, 0, 0); doc.Template.Stamps.Add(header); PdfImage footerImage = PdfImage.FromFile(@"Footer.png"); y = pageSize.Height - footerImage.PhysicalDimension.Height; PointF footerLocation = new PointF(-margin.Left, y); PdfPageTemplateElement footer = new PdfPageTemplateElement(footerLocation, footerImage.PhysicalDimension); footer.Foreground = false; footer.Graphics.SetTransparency(0.5f); footer.Graphics.DrawImage(footerImage, 0, 0); doc.Template.Stamps.Add(footer); } } }
Imports System.Drawing Imports Spire.Pdf Imports Spire.Pdf.Graphics Imports System.Text Imports Spire.Pdf.AutomaticFields Namespace Template Friend Class Program Shared Sub Main(ByVal args() As String) 'Create a pdf document. Dim doc As New PdfDocument() doc.ViewerPreferences.PageLayout = PdfPageLayout.TwoColumnLeft 'margin Dim unitCvtr As New PdfUnitConvertor() Dim margin As New PdfMargins() margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point) margin.Bottom = margin.Top margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point) margin.Right = margin.Left SetDocumentTemplate(doc, PdfPageSize.A4, margin) 'create section Dim section As PdfSection = doc.Sections.Add() section.PageSettings.Size = PdfPageSize.A4 section.PageSettings.Margins = New PdfMargins(0) SetSectionTemplate(section, PdfPageSize.A4, margin, "Section 1") ' Create one page Dim page As PdfNewPage = section.Pages.Add() 'Draw page DrawPage(page) page = section.Pages.Add() DrawPage(page) page = section.Pages.Add() DrawPage(page) page = section.Pages.Add() DrawPage(page) page = section.Pages.Add() DrawPage(page) 'Save pdf file. doc.SaveToFile("Template.pdf") doc.Close() 'Launching the Pdf file. Process.Start("Template.pdf") End Sub Private Shared Sub DrawPage(ByVal page As PdfNewPage) Dim pageWidth As Single = page.Canvas.ClientSize.Width Dim y As Single = 0 'title y = y + 5 Dim brush2 As PdfBrush = New PdfSolidBrush(Color.Black) Dim font2 As New PdfTrueTypeFont(New Font("Arial", 16.0F, FontStyle.Bold)) Dim format2 As New PdfStringFormat(PdfTextAlignment.Center) format2.CharacterSpacing = 1.0F Dim text As String = "Summary of Science" page.Canvas.DrawString(text, font2, brush2, pageWidth / 2, y, format2) Dim size As SizeF = font2.MeasureString(text, format2) y = y + size.Height + 6 'icon Dim image As PdfImage = PdfImage.FromFile("Wikipedia_Science.png") page.Canvas.DrawImage(image, New PointF(pageWidth - image.PhysicalDimension.Width, y)) Dim imageLeftSpace As Single = pageWidth - image.PhysicalDimension.Width - 2 Dim imageBottom As Single = image.PhysicalDimension.Height + y 'refenrence content Dim font3 As New PdfTrueTypeFont(New Font("Arial", 9.0F)) Dim format3 As New PdfStringFormat() format3.ParagraphIndent = font3.Size * 2 format3.MeasureTrailingSpaces = True format3.LineSpacing = font3.Size * 1.5F Dim text1 As String = "(All text and picture from " Dim text2 As String = "Wikipedia" Dim text3 As String = ", the free encyclopedia)" page.Canvas.DrawString(text1, font3, brush2, 0, y, format3) size = font3.MeasureString(text1, format3) Dim x1 As Single = size.Width format3.ParagraphIndent = 0 Dim font4 As New PdfTrueTypeFont(New Font("Arial", 9.0F, FontStyle.Underline)) Dim brush3 As PdfBrush = PdfBrushes.Blue page.Canvas.DrawString(text2, font4, brush3, x1, y, format3) size = font4.MeasureString(text2, format3) x1 = x1 + size.Width page.Canvas.DrawString(text3, font3, brush2, x1, y, format3) y = y + size.Height 'content Dim format4 As New PdfStringFormat() text = System.IO.File.ReadAllText("Summary_of_Science.txt") Dim font5 As New PdfTrueTypeFont(New Font("Arial", 10.0F)) format4.LineSpacing = font5.Size * 1.5F Dim textLayouter As New PdfStringLayouter() Dim imageLeftBlockHeight As Single = imageBottom - y Dim result As PdfStringLayoutResult _ = textLayouter.Layout(text, font5, format4, New SizeF(imageLeftSpace, imageLeftBlockHeight)) If result.ActualSize.Height < imageBottom - y Then imageLeftBlockHeight = imageLeftBlockHeight + result.LineHeight result = textLayouter.Layout(text, font5, format4, New SizeF(imageLeftSpace, imageLeftBlockHeight)) End If For Each line As LineInfo In result.Lines page.Canvas.DrawString(line.Text, font5, brush2, 0, y, format4) y = y + result.LineHeight Next line Dim textWidget As New PdfTextWidget(result.Remainder, font5, brush2) Dim textLayout As New PdfTextLayout() textLayout.Break = PdfLayoutBreakType.FitPage textLayout.Layout = PdfLayoutType.Paginate Dim bounds As New RectangleF(New PointF(0, y), page.Canvas.ClientSize) textWidget.StringFormat = format4 textWidget.Draw(page, bounds, textLayout) End Sub Private Shared Sub SetSectionTemplate(ByVal section As PdfSection, ByVal pageSize As SizeF, _ ByVal margin As PdfMargins, ByVal label As String) Dim leftSpace As New PdfPageTemplateElement(margin.Left, pageSize.Height) leftSpace.Foreground = True section.Template.OddLeft = leftSpace Dim font As New PdfTrueTypeFont(New Font("Arial", 9.0F, FontStyle.Italic)) Dim format As New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle) Dim y As Single = (pageSize.Height - margin.Top - margin.Bottom) * (1 - 0.618F) Dim bounds As New RectangleF(10, y, margin.Left - 20, font.Height + 6) leftSpace.Graphics.DrawRectangle(PdfBrushes.OrangeRed, bounds) leftSpace.Graphics.DrawString(label, font, PdfBrushes.White, bounds, format) Dim rightSpace As New PdfPageTemplateElement(margin.Right, pageSize.Height) rightSpace.Foreground = True section.Template.EvenRight = rightSpace bounds = New RectangleF(10, y, margin.Right - 20, font.Height + 6) rightSpace.Graphics.DrawRectangle(PdfBrushes.SaddleBrown, bounds) rightSpace.Graphics.DrawString(label, font, PdfBrushes.White, bounds, format) End Sub Private Shared Sub SetDocumentTemplate(ByVal doc As PdfDocument, ByVal pageSize As SizeF, _ ByVal margin As PdfMargins) Dim leftSpace As New PdfPageTemplateElement(margin.Left, pageSize.Height) doc.Template.Left = leftSpace Dim topSpace As New PdfPageTemplateElement(pageSize.Width, margin.Top) topSpace.Foreground = True doc.Template.Top = topSpace 'draw header label Dim font As New PdfTrueTypeFont(New Font("Arial", 9.0F, FontStyle.Italic)) Dim format As New PdfStringFormat(PdfTextAlignment.Right) Dim label As String = "Demo of Spire.Pdf" Dim size As SizeF = font.MeasureString(label, format) Dim y As Single = topSpace.Height - font.Height - 1 Dim pen As New PdfPen(Color.Black, 0.75F) topSpace.Graphics.SetTransparency(0.5F) topSpace.Graphics.DrawLine(pen, margin.Left, y, pageSize.Width - margin.Right, y) y = y - 1 - size.Height topSpace.Graphics.DrawString(label, font, PdfBrushes.Black, pageSize.Width - margin.Right, y, format) Dim rightSpace As New PdfPageTemplateElement(margin.Right, pageSize.Height) doc.Template.Right = rightSpace Dim bottomSpace As New PdfPageTemplateElement(pageSize.Width, margin.Bottom) bottomSpace.Foreground = True doc.Template.Bottom = bottomSpace 'draw footer label y = font.Height + 1 bottomSpace.Graphics.SetTransparency(0.5F) bottomSpace.Graphics.DrawLine(pen, margin.Left, y, pageSize.Width - margin.Right, y) y = y + 1 Dim pageNumber As New PdfPageNumberField() Dim pageCount As New PdfPageCountField() Dim pageNumberLabel As New PdfCompositeField() pageNumberLabel.AutomaticFields = New PdfAutomaticField() {pageNumber, pageCount} pageNumberLabel.Brush = PdfBrushes.Black pageNumberLabel.Font = font pageNumberLabel.StringFormat = format pageNumberLabel.Text = "page {0} of {1}" pageNumberLabel.Draw(bottomSpace.Graphics, pageSize.Width - margin.Right, y) Dim headerImage As PdfImage = PdfImage.FromFile("Header.png") Dim pageLeftTop As New PointF(-margin.Left, -margin.Top) Dim header As New PdfPageTemplateElement(pageLeftTop, headerImage.PhysicalDimension) header.Foreground = False header.Graphics.SetTransparency(0.5F) header.Graphics.DrawImage(headerImage, 0, 0) doc.Template.Stamps.Add(header) Dim footerImage As PdfImage = PdfImage.FromFile("Footer.png") y = pageSize.Height - footerImage.PhysicalDimension.Height Dim footerLocation As New PointF(-margin.Left, y) Dim footer As New PdfPageTemplateElement(footerLocation, footerImage.PhysicalDimension) footer.Foreground = False footer.Graphics.SetTransparency(0.5F) footer.Graphics.DrawImage(footerImage, 0, 0) doc.Template.Stamps.Add(footer) End Sub End Class End Namespace
PDF TextLayout in C#, VB.NET
The sample demonstrates how to work with text layout in PDF document.
using System; using System.Drawing; using Spire.Pdf; using Spire.Pdf.Graphics; namespace TextLayout { class Program { static void Main(string[] args) { //Create a pdf document. PdfDocument doc = new PdfDocument(); // Create one page PdfPageBase page = doc.Pages.Add(); float pageWidth = page.Canvas.ClientSize.Width; float y = 0; //page header PdfPen pen1 = new PdfPen(Color.LightGray, 1f); PdfBrush brush1 = new PdfSolidBrush(Color.LightGray); PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 8f, FontStyle.Italic)); PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Right); String text = "Demo of Spire.Pdf"; page.Canvas.DrawString(text, font1, brush1, pageWidth, y, format1); SizeF size = font1.MeasureString(text, format1); y = y + size.Height + 1; page.Canvas.DrawLine(pen1, 0, y, pageWidth, y); //title y = y + 5; PdfBrush brush2 = new PdfSolidBrush(Color.Black); PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold)); PdfStringFormat format2 = new PdfStringFormat(PdfTextAlignment.Center); format2.CharacterSpacing = 1f; text = "Summary of Science"; page.Canvas.DrawString(text, font2, brush2, pageWidth / 2, y, format2); size = font2.MeasureString(text, format2); y = y + size.Height + 6; //icon PdfImage image = PdfImage.FromFile("Wikipedia_Science.png"); page.Canvas.DrawImage(image, new PointF(pageWidth - image.PhysicalDimension.Width, y)); float imageLeftSpace = pageWidth - image.PhysicalDimension.Width - 2; float imageBottom = image.PhysicalDimension.Height + y; //refenrence content PdfTrueTypeFont font3 = new PdfTrueTypeFont(new Font("Arial", 9f)); PdfStringFormat format3 = new PdfStringFormat(); format3.ParagraphIndent = font3.Size * 2; format3.MeasureTrailingSpaces = true; format3.LineSpacing = font3.Size * 1.5f; String text1 = "(All text and picture from "; String text2 = "Wikipedia"; String text3 = ", the free encyclopedia)"; page.Canvas.DrawString(text1, font3, brush2, 0, y, format3); size = font3.MeasureString(text1, format3); float x1 = size.Width; format3.ParagraphIndent = 0; PdfTrueTypeFont font4 = new PdfTrueTypeFont(new Font("Arial", 9f, FontStyle.Underline)); PdfBrush brush3 = PdfBrushes.Blue; page.Canvas.DrawString(text2, font4, brush3, x1, y, format3); size = font4.MeasureString(text2, format3); x1 = x1 + size.Width; page.Canvas.DrawString(text3, font3, brush2, x1, y, format3); y = y + size.Height; //content PdfStringFormat format4 = new PdfStringFormat(); text = System.IO.File.ReadAllText("Summary_of_Science.txt"); PdfTrueTypeFont font5 = new PdfTrueTypeFont(new Font("Arial", 10f)); format4.LineSpacing = font5.Size * 1.5f; PdfStringLayouter textLayouter = new PdfStringLayouter(); float imageLeftBlockHeight = imageBottom - y; PdfStringLayoutResult result = textLayouter.Layout(text, font5, format4, new SizeF(imageLeftSpace, imageLeftBlockHeight)); if (result.ActualSize.Height < imageBottom - y) { imageLeftBlockHeight = imageLeftBlockHeight + result.LineHeight; result = textLayouter.Layout(text, font5, format4, new SizeF(imageLeftSpace, imageLeftBlockHeight)); } foreach (LineInfo line in result.Lines) { page.Canvas.DrawString(line.Text, font5, brush2, 0, y, format4); y = y + result.LineHeight; } PdfTextWidget textWidget = new PdfTextWidget(result.Remainder, font5, brush2); PdfTextLayout textLayout = new PdfTextLayout(); textLayout.Break = PdfLayoutBreakType.FitPage; textLayout.Layout = PdfLayoutType.Paginate; RectangleF bounds = new RectangleF(new PointF(0, y), page.Canvas.ClientSize); textWidget.StringFormat = format4; textWidget.Draw(page, bounds, textLayout); //Save pdf file. doc.SaveToFile("TextLayout.pdf"); doc.Close(); //Launching the Pdf file. System.Diagnostics.Process.Start("TextLayout.pdf"); } } }
Imports System.Drawing Imports Spire.Pdf Imports Spire.Pdf.Graphics Namespace TextLayout Friend Class Program Shared Sub Main(ByVal args() As String) 'Create a pdf document. Dim doc As New PdfDocument() ' Create one page Dim page As PdfPageBase = doc.Pages.Add() Dim pageWidth As Single = page.Canvas.ClientSize.Width Dim y As Single = 0 'page header Dim pen1 As New PdfPen(Color.LightGray, 1.0F) Dim brush1 As PdfBrush = New PdfSolidBrush(Color.LightGray) Dim font1 As New PdfTrueTypeFont(New Font("Arial", 8.0F, FontStyle.Italic)) Dim format1 As New PdfStringFormat(PdfTextAlignment.Right) Dim text As String = "Demo of Spire.Pdf" page.Canvas.DrawString(text, font1, brush1, pageWidth, y, format1) Dim size As SizeF = font1.MeasureString(text, format1) y = y + size.Height + 1 page.Canvas.DrawLine(pen1, 0, y, pageWidth, y) 'title y = y + 5 Dim brush2 As PdfBrush = New PdfSolidBrush(Color.Black) Dim font2 As New PdfTrueTypeFont(New Font("Arial", 16.0F, FontStyle.Bold)) Dim format2 As New PdfStringFormat(PdfTextAlignment.Center) format2.CharacterSpacing = 1.0F text = "Summary of Science" page.Canvas.DrawString(text, font2, brush2, pageWidth / 2, y, format2) size = font2.MeasureString(text, format2) y = y + size.Height + 6 'icon Dim image As PdfImage = PdfImage.FromFile("Wikipedia_Science.png") page.Canvas.DrawImage(image, New PointF(pageWidth - image.PhysicalDimension.Width, y)) Dim imageLeftSpace As Single = pageWidth - image.PhysicalDimension.Width - 2 Dim imageBottom As Single = image.PhysicalDimension.Height + y 'refenrence content Dim font3 As New PdfTrueTypeFont(New Font("Arial", 9.0F)) Dim format3 As New PdfStringFormat() format3.ParagraphIndent = font3.Size * 2 format3.MeasureTrailingSpaces = True format3.LineSpacing = font3.Size * 1.5F Dim text1 As String = "(All text and picture from " Dim text2 As String = "Wikipedia" Dim text3 As String = ", the free encyclopedia)" page.Canvas.DrawString(text1, font3, brush2, 0, y, format3) size = font3.MeasureString(text1, format3) Dim x1 As Single = size.Width format3.ParagraphIndent = 0 Dim font4 As New PdfTrueTypeFont(New Font("Arial", 9.0F, FontStyle.Underline)) Dim brush3 As PdfBrush = PdfBrushes.Blue page.Canvas.DrawString(text2, font4, brush3, x1, y, format3) size = font4.MeasureString(text2, format3) x1 = x1 + size.Width page.Canvas.DrawString(text3, font3, brush2, x1, y, format3) y = y + size.Height 'content Dim format4 As New PdfStringFormat() text = System.IO.File.ReadAllText("Summary_of_Science.txt") Dim font5 As New PdfTrueTypeFont(New Font("Arial", 10.0F)) format4.LineSpacing = font5.Size * 1.5F Dim textLayouter As New PdfStringLayouter() Dim imageLeftBlockHeight As Single = imageBottom - y Dim result As PdfStringLayoutResult _ = textLayouter.Layout(text, font5, format4, New SizeF(imageLeftSpace, imageLeftBlockHeight)) If result.ActualSize.Height < imageBottom - y Then imageLeftBlockHeight = imageLeftBlockHeight + result.LineHeight result = textLayouter.Layout(text, font5, format4, New SizeF(imageLeftSpace, imageLeftBlockHeight)) End If For Each line As LineInfo In result.Lines page.Canvas.DrawString(line.Text, font5, brush2, 0, y, format4) y = y + result.LineHeight Next line Dim textWidget As New PdfTextWidget(result.Remainder, font5, brush2) Dim textLayout As New PdfTextLayout() textLayout.Break = PdfLayoutBreakType.FitPage textLayout.Layout = PdfLayoutType.Paginate Dim bounds As New RectangleF(New PointF(0, y), page.Canvas.ClientSize) textWidget.StringFormat = format4 textWidget.Draw(page, bounds, textLayout) 'Save pdf file. doc.SaveToFile("TextLayout.pdf") doc.Close() 'Launching the Pdf file. Process.Start("TextLayout.pdf") End Sub End Class End Namespace
PDF DrawImage in C#, VB.NET
The sample demonstrates how to draw image in PDF document.
using System; using System.Drawing; using Spire.Pdf; using Spire.Pdf.Graphics; namespace DrawImage { class Program { static void Main(string[] args) { //Create a pdf document. PdfDocument doc = new PdfDocument(); // Create one page PdfPageBase page = doc.Pages.Add(); TransformText(page); DrawImage(page); TransformImage(page); //Save pdf file. doc.SaveToFile("DrawImage.pdf"); doc.Close(); //Launching the Pdf file. System.Diagnostics.Process.Start("DrawImage.pdf"); } private static void TransformImage(PdfPageBase page) { //save graphics state PdfGraphicsState state = page.Canvas.Save(); //Draw the text - transform PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 18f); PdfSolidBrush brush1 = new PdfSolidBrush(Color.Blue); PdfSolidBrush brush2 = new PdfSolidBrush(Color.CadetBlue); PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Center); page.Canvas.TranslateTransform(page.Canvas.ClientSize.Width / 2, 20); page.Canvas.DrawString("Sales Report Chart", font, brush1, 0, 0, format); page.Canvas.ScaleTransform(1f, -0.8f); page.Canvas.DrawString("Sales Report Chart", font, brush2, 0, -2 * 18 * 1.2f, format); //restor graphics page.Canvas.Restore(state); } private static void DrawImage(PdfPageBase page) { PdfImage image = PdfImage.FromFile(@"SalesReportChart.png"); float width = image.Width * 0.75f; float height = image.Height * 0.75f; float x = (page.Canvas.ClientSize.Width - width) / 2; page.Canvas.DrawImage(image, x, 60, width, height); } private static void TransformText(PdfPageBase page) { PdfImage image = PdfImage.FromFile(@"SalesReportChart.png"); int skewX = 20; int skewY = 20; float scaleX = 0.2f; float scaleY = 0.6f; int width = (int)((image.Width + image.Height * Math.Tan(Math.PI * skewX / 180)) * scaleX); int height = (int)((image.Height + image.Width * Math.Tan(Math.PI * skewY / 180)) * scaleY); PdfTemplate template = new PdfTemplate(width, height); template.Graphics.ScaleTransform(scaleX, scaleY); template.Graphics.SkewTransform(skewX, skewY); template.Graphics.DrawImage(image, 0, 0); //save graphics state PdfGraphicsState state = page.Canvas.Save(); page.Canvas.TranslateTransform(page.Canvas.ClientSize.Width - 50, 260); float offset = (page.Canvas.ClientSize.Width - 100) / 12; for (int i = 0; i < 12; i++) { page.Canvas.TranslateTransform(-offset, 0); page.Canvas.SetTransparency(i / 12.0f); page.Canvas.DrawTemplate(template, new PointF(0, 0)); } //restor graphics page.Canvas.Restore(state); } } }
Imports System.Drawing Imports Spire.Pdf Imports Spire.Pdf.Graphics Namespace DrawImage Friend Class Program Shared Sub Main(ByVal args() As String) 'Create a pdf document. Dim doc As New PdfDocument() ' Create one page Dim page As PdfPageBase = doc.Pages.Add() TransformText(page) DrawImage(page) TransformImage(page) 'Save pdf file. doc.SaveToFile("DrawImage.pdf") doc.Close() 'Launching the Pdf file. Process.Start("DrawImage.pdf") End Sub Private Shared Sub TransformImage(ByVal page As PdfPageBase) 'save graphics state Dim state As PdfGraphicsState = page.Canvas.Save() 'Draw the text - transform Dim font As New PdfFont(PdfFontFamily.Helvetica, 18.0F) Dim brush1 As New PdfSolidBrush(Color.Blue) Dim brush2 As New PdfSolidBrush(Color.CadetBlue) Dim format As New PdfStringFormat(PdfTextAlignment.Center) page.Canvas.TranslateTransform(page.Canvas.ClientSize.Width \ 2, 20) page.Canvas.DrawString("Sales Report Chart", font, brush1, 0, 0, format) page.Canvas.ScaleTransform(1.0F, -0.8F) page.Canvas.DrawString("Sales Report Chart", font, brush2, 0, -2 * 18 * 1.2F, format) 'restor graphics page.Canvas.Restore(state) End Sub Private Shared Sub DrawImage(ByVal page As PdfPageBase) Dim image As PdfImage = PdfImage.FromFile("SalesReportChart.png") Dim width As Single = image.Width * 0.75F Dim height As Single = image.Height * 0.75F Dim x As Single = (page.Canvas.ClientSize.Width - width) / 2 page.Canvas.DrawImage(image, x, 60, width, height) End Sub Private Shared Sub TransformText(ByVal page As PdfPageBase) Dim image As PdfImage = PdfImage.FromFile("SalesReportChart.png") Dim skewX As Integer = 20 Dim skewY As Integer = 20 Dim scaleX As Single = 0.2F Dim scaleY As Single = 0.6F Dim width As Integer = CInt(Fix((image.Width + image.Height * Math.Tan(Math.PI * skewX \ 180)) * scaleX)) Dim height As Integer = CInt(Fix((image.Height + image.Width * Math.Tan(Math.PI * skewY \ 180)) * scaleY)) Dim template As New PdfTemplate(width, height) template.Graphics.ScaleTransform(scaleX, scaleY) template.Graphics.SkewTransform(skewX, skewY) template.Graphics.DrawImage(image, 0, 0) 'save graphics state Dim state As PdfGraphicsState = page.Canvas.Save() page.Canvas.TranslateTransform(page.Canvas.ClientSize.Width - 50, 260) Dim offset As Single = (page.Canvas.ClientSize.Width - 100) / 12 For i As Integer = 0 To 11 page.Canvas.TranslateTransform(-offset, 0) page.Canvas.SetTransparency(i / 12.0F) page.Canvas.DrawTemplate(template, New PointF(0, 0)) Next i 'restor graphics page.Canvas.Restore(state) End Sub End Class End Namespace
PDF Image in C#, VB.NET
The sample demonstrates how to insert an image to a PDF document.
using System.Drawing; using Spire.Pdf; using Spire.Pdf.Graphics; namespace Image { class Program { static void Main(string[] args) { //Create a pdf document. PdfDocument doc = new PdfDocument(); // Create one page PdfPageBase page = doc.Pages.Add(); //Draw the text page.Canvas.DrawString("Hello, World!", new PdfFont(PdfFontFamily.Helvetica, 30f), new PdfSolidBrush(Color.Black), 10, 10); //Draw the image PdfImage image = PdfImage.FromFile(@"SalesReportChart.png"); float width = image.Width * 0.75f; float height = image.Height * 0.75f; float x = (page.Canvas.ClientSize.Width - width) / 2; page.Canvas.DrawImage(image, x, 60, width, height); //Save pdf file. doc.SaveToFile("Image.pdf"); doc.Close(); //Launching the Pdf file. System.Diagnostics.Process.Start("Image.pdf"); } } }
Imports System.Drawing Imports Spire.Pdf Imports Spire.Pdf.Graphics Namespace Image Friend Class Program Shared Sub Main(ByVal args() As String) 'Create a pdf document. Dim doc As New PdfDocument() ' Create one page Dim page As PdfPageBase = doc.Pages.Add() 'Draw the text page.Canvas.DrawString("Hello, World!", _ New PdfFont(PdfFontFamily.Helvetica, 30.0F), _ New PdfSolidBrush(Color.Black), 10, 10) 'Draw the image Dim image As PdfImage = PdfImage.FromFile("SalesReportChart.png") Dim width As Single = image.Width * 0.75F Dim height As Single = image.Height * 0.75F Dim x As Single = (page.Canvas.ClientSize.Width - width) / 2 page.Canvas.DrawImage(image, x, 60, width, height) 'Save pdf file. doc.SaveToFile("Image.pdf") doc.Close() 'Launching the Pdf file. Process.Start("Image.pdf") End Sub End Class End Namespace
Word Image in C#, VB.NET
The sample demonstrates how to insert an image into a Word document.
private void button1_Click(object sender, EventArgs e) { //Create word document Document document = new Document(); InsertImage(document.AddSection()); //Save doc file. document.SaveToFile("Sample.doc",FileFormat.Doc); //Launching the MS Word file. WordDocViewer("Sample.doc"); } private void InsertImage(Section section) { Paragraph paragraph = section.AddParagraph(); paragraph.AppendText("The sample demonstrates how to insert a image into a document."); paragraph.ApplyStyle(BuiltinStyle.Heading2); paragraph = section.AddParagraph(); paragraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left; paragraph.AppendPicture(Image.Properties.Resources.Word); } private void WordDocViewer(string fileName) { try { System.Diagnostics.Process.Start(fileName); } catch { } }
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles button1.Click 'Create word document Dim document_Renamed As New Document() InsertImage(document_Renamed.AddSection()) 'Save doc file. document_Renamed.SaveToFile("Sample.doc",FileFormat.Doc) 'Launching the MS Word file. WordDocViewer("Sample.doc") End Sub Private Sub InsertImage(ByVal section_Renamed As Section) Dim paragraph_Renamed As Paragraph = section_Renamed.AddParagraph() paragraph_Renamed.AppendText("The sample demonstrates how to insert a image into a document.") paragraph_Renamed.ApplyStyle(BuiltinStyle.Heading2) paragraph_Renamed = section_Renamed.AddParagraph() paragraph_Renamed.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left paragraph_Renamed.AppendPicture(My.Resources.Word) End Sub Private Sub WordDocViewer(ByVal fileName As String) Try Process.Start(fileName) Catch End Try End Sub
EXCEL Write Images in C#, VB.NET
The sample demonstrates how to write images to spreadsheet.
private void btnRun_Click(object sender, System.EventArgs e) { Workbook workbook = new Workbook(); Worksheet sheet = workbook.Worksheets[0]; sheet.Pictures.Add(1,1,@"..\..\..\..\..\..\Data\day.jpg"); workbook.SaveToFile("sample.xls"); ExcelDocViewer(workbook.FileName); } private void ExcelDocViewer( string fileName ) { try { System.Diagnostics.Process.Start(fileName); } catch{} }
Private Sub btnRun_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRun.Click Dim workbook As Workbook = New Workbook() Dim sheet As Worksheet = workbook.Worksheets(0) sheet.Pictures.Add(1,1,"..\..\..\..\..\..\Data\day.jpg") workbook.SaveToFile("sample.xls") ExcelDocViewer(workbook.FileName) End Sub Private Sub ExcelDocViewer(ByVal fileName As String) Try System.Diagnostics.Process.Start(fileName) Catch End Try End Sub