I have created a PDF using PdfPageTemplateElement to create a header. This works fine but there is a large blank space above this header. If I reduce the top margin then it loses the top of the header.
How can I get rid of this blank space?
static void Main(string[] args)
{
PdfDocument doc = new PdfDocument();
doc.Pages.Add(); doc.Pages.Add();
doc.PageSettings.Size = PdfPageSize.A4;
//reset the default margins to 0
doc.PageSettings.Margins = new PdfMargins(0);
PdfMargins margins = new PdfMargins(60, 35, 60, 60);
doc.Template.Top = CreateHeaderTemplate(doc, margins);
doc.SaveToFile("PdfHeader.pdf");
}
static PdfPageTemplateElement CreateHeaderTemplate(PdfDocument doc, PdfMargins margins)
{
SizeF pageSize = doc.PageSettings.Size;
PdfPageTemplateElement headerSpace = new PdfPageTemplateElement(pageSize.Width, margins.Top);
headerSpace.Foreground = false;
float x = margins.Left;
float y = 0;
PdfImage headerImage = PdfImage.FromFile("icon.png");
float width = headerImage.Width / 3;
float height = headerImage.Height / 3;
headerSpace.Graphics.DrawImage(headerImage, x, margins.Top - height - 2, width, height);
PdfPen pen = new PdfPen(PdfBrushes.Gray, 1);
headerSpace.Graphics.DrawLine(pen, x, y + margins.Top - 2, pageSize.Width - x, y + margins.Top - 2);
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Impact", 25f, FontStyle.Bold));
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
String headerText = "HEADER TEXT";
SizeF size = font.MeasureString(headerText, format);
headerSpace.Graphics.DrawString(headerText, font, PdfBrushes.Gray, pageSize.Width - x - size.Width - 2, margins.Top - (size.Height + 5), format);
return headerSpace;
}'Imports GymdataClubMananger.SQLCommon
Imports vb = Microsoft.VisualBasic
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Tables
Imports Spire.Pdf.AutomaticFields
Imports Spire.Pdf.Widget
Imports Spire.PdfViewer.Forms
Imports CommonRoutines.CommonMgmtRoutines
Imports System.Drawing.Printing
Public Class CreatePDF
Shared Rept As PdfDocument
Shared f6 As PdfTrueTypeFont
Shared f8 As PdfTrueTypeFont
Shared f10 As PdfTrueTypeFont
Shared f12 As PdfTrueTypeFont
Shared f14 As PdfTrueTypeFont
Shared f16 As PdfTrueTypeFont
Shared HeadFont As PdfTrueTypeFont
Shared BodyFont As PdfTrueTypeFont
Shared themargin As New PdfMargins()
Shared page As PdfPageBase
Shared PrintWidth As Single
Shared PrintHeight As Single
Shared pdfBlackBrush As PdfSolidBrush = New PdfSolidBrush(Color.Black)
Shared NextYPosition As Single
Shared col_tab As DataTable
Shared Preview As Boolean
Shared Portrait As Boolean
Shared TheFileName As String
Shared TheFont As Integer
Shared MaxRows As Integer
Shared TableWidth As Decimal
Shared CSVLine As String = ""
Shared Sub PDF_Create(ByRef thedata As DataTable, ByVal TheHeader As String, ByVal ReportName As String, ByVal ShowPrintPreview As Boolean, ByVal ExtractCSV As Boolean)
Preview = ShowPrintPreview
If ExtractCSV = True Then
Extract_CSV(thedata, TheHeader)
Else
Dim def_Dataset As New DataSet
SQLString = "select * from tblReportDefinition where ReportName = '" & ReportName & "'"
CR_GetSQLDataset(SQLString, def_Dataset)
If def_Dataset.Tables(0).Rows.Count = 0 Then
TheFileName = ReportName.Replace(" ", "_")
TheFont = 6
MaxRows = 300
Portrait = True
Else
TheFileName = def_Dataset.Tables(0).Rows(0).Item("ReportName").ToString
TheFont = CInt(def_Dataset.Tables(0).Rows(0).Item("Font").ToString)
MaxRows = CInt(def_Dataset.Tables(0).Rows(0).Item("MaxRows").ToString)
Portrait = CBool(def_Dataset.Tables(0).Rows(0).Item("Portrait").ToString)
End If
Dim tempfont6 As New System.Drawing.Font("Arial", 6.0F, FontStyle.Regular)
f6 = New PdfTrueTypeFont(tempfont6)
Dim tempfont8 As New System.Drawing.Font("Arial", 8.0F, FontStyle.Regular)
f8 = New PdfTrueTypeFont(tempfont8)
Dim tempfont10 As New System.Drawing.Font("Arial", 10.0F, FontStyle.Regular)
f10 = New PdfTrueTypeFont(tempfont10)
Dim tempfont12 As New System.Drawing.Font("Arial", 12.0F, FontStyle.Regular)
f12 = New PdfTrueTypeFont(tempfont12)
Dim tempfont14 As New System.Drawing.Font("Arial", 14.0F, FontStyle.Regular)
f14 = New PdfTrueTypeFont(tempfont14)
Dim tempfont16 As New System.Drawing.Font("Arial", 16.0F, FontStyle.Regular)
f16 = New PdfTrueTypeFont(tempfont16)
Select Case TheFont
Case 6
HeadFont = f8
BodyFont = f6
Case 8
HeadFont = f10
BodyFont = f8
Case 10
HeadFont = f12
BodyFont = f10
Case 12
HeadFont = f14
BodyFont = f12
Case 14
HeadFont = f16
BodyFont = f14
End Select
col_tab = New DataTable
col_tab.Columns.Add("ColWidth", Type.GetType("System.Decimal"))
col_tab.Columns.Add("ColType", Type.GetType("System.String"))
col_tab.Columns.Add("ColName", Type.GetType("System.String"))
Dim col_width As Single = 0
Dim col_row As DataRow
For col_no As Integer = 0 To thedata.Columns.Count - 1
col_width = HeadFont.MeasureString(thedata.Columns(col_no).ColumnName.ToString()).Width
col_row = col_tab.NewRow()
If col_width * 1.5 > 130 Then
col_width = 130
Else
col_row("ColWidth") = col_width * 1.5
End If
col_row("ColType") = thedata.Columns(col_no).DataType.Name
col_row("ColName") = thedata.Columns(col_no).ColumnName
col_tab.Rows.Add(col_row)
Next
For rowno As Integer = 0 To thedata.Rows.Count - 1
For col_no As Integer = 0 To thedata.Columns.Count - 1
col_width = CSng(CDbl(BodyFont.MeasureString(thedata.Rows(rowno).Item(col_no).ToString()).Width) * 1.5)
Dim existing_width As Single = CSng(col_tab.Rows(col_no).Item("ColWidth").ToString)
If existing_width < col_width Then
If col_width > 130 Then
col_tab.Rows(col_no).Item("ColWidth") = 130
Else
col_tab.Rows(col_no).Item("ColWidth") = col_width
End If
End If
Next
Next
TableWidth = 0
For rowno As Integer = 0 To col_tab.Rows.Count - 1
TableWidth += CDec(col_tab.Rows(rowno).Item("ColWidth").ToString) + 10
Next
' col_tab now has the max width of each column
Dim print_tab As DataTable
print_tab = thedata.Clone()
Dim print_no As Integer = 0
Dim reccount As Integer = 0
If thedata.Rows.Count > MaxRows Then
For row_count = 1 To thedata.Rows.Count - 1
If reccount = MaxRows Then
print_no += 1
Do_It(print_tab, TheHeader, TheFileName & LTrim(RTrim(Str(print_no))))
print_tab.Clear()
reccount = 0
End If
reccount += 1
print_tab.Rows.Add(thedata.Rows(row_count).ItemArray)
Next
If print_tab.Rows.Count > 0 Then
print_no += 1
Do_It(print_tab, TheHeader, TheFileName & LTrim(RTrim(Str(print_no))))
End If
Else
If thedata.Rows.Count > 0 Then
Do_It(thedata, TheHeader, TheFileName)
End If
End If
col_tab.Dispose()
End If
End Sub
Shared Function CreateHeaderTemplate(doc As PdfDocument, margins As PdfMargins, theheader As String) As PdfPageTemplateElement
Dim pageSize As SizeF = doc.PageSettings.Size
Dim headerSpace As New PdfPageTemplateElement(pageSize.Width, margins.Top)
headerSpace.Foreground = False
Dim x As Single = margins.Left
Dim y As Single = 0
Dim headerImage As PdfImage
CR_Refresh_Image()
Dim width As Single
Dim height As Single
If varClubLogoStr <> "" Or varClubLogoStr Is Nothing Then
Dim isize As Size = New Size(186, 186)
Dim scaledimage As Bitmap = New Bitmap(varClubLogo, isize)
headerImage = PdfImage.FromImage(scaledimage)
width = headerImage.Width / 3
height = headerImage.Height / 3
headerSpace.Graphics.DrawImage(headerImage, pageSize.Width - margins.Right - width, margins.Top - height - 2, width, height)
'headerSpace.Graphics.DrawImage(headerImage, pageSize.Width - margins.Right - width, -40, width, height)
End If
Dim pen As New PdfPen(PdfBrushes.Black, 1)
headerSpace.Graphics.DrawLine(pen, 0, margins.Top - height + 60, pageSize.Width, margins.Top - height + 60)
Dim font As New PdfTrueTypeFont(New Font("Arial", 14.0F, FontStyle.Bold))
Dim format As New PdfStringFormat(PdfTextAlignment.Left)
Dim size As SizeF = font.MeasureString(theheader, format)
headerSpace.Graphics.DrawString(theheader, font, PdfBrushes.Black, 0, margins.Top - (size.Height + 15), format)
Dim temp_font = New Font("Arial", 8.0F, FontStyle.Regular)
Dim club_font As New PdfTrueTypeFont(temp_font)
Dim club_size As SizeF = club_font.MeasureString(varClubName)
'headerSpace.Graphics.DrawString(varClubName, club_font, PdfBrushes.Black, pageSize.Width - margins.Right - club_size.Width, margins.Top - height + 50)
headerSpace.Graphics.DrawString(varClubName, club_font, PdfBrushes.Black, pageSize.Width - margins.Right - club_size.Width, margins.Top - height + 50)
Return headerSpace
End Function
Private Shared Function CreateFooterTemplate(doc As PdfDocument, margins As PdfMargins) As PdfPageTemplateElement
'get page size
Dim pageSize As SizeF = doc.PageSettings.Size
'create a PdfPageTemplateElement object which works as footer space
Dim footerSpace As New PdfPageTemplateElement(pageSize.Width, margins.Bottom)
footerSpace.Foreground = False
'declare two float variables
Dim x As Single = margins.Left
Dim y As Single = 0
'draw line in footer space
Dim pen As New PdfPen(PdfBrushes.Gray, 1)
'footerSpace.Graphics.DrawLine(pen, x, y, pageSize.Width - x, y)
footerSpace.Graphics.DrawLine(pen, 0, y, pageSize.Width, y)
'draw text in footer space
y = y + 5
Dim font As New PdfTrueTypeFont(New Font("Arial", 10.0F), True)
Dim Left_just As New PdfStringFormat(PdfTextAlignment.Left)
Dim Centre_just As New PdfStringFormat(PdfTextAlignment.Center)
Dim footerText As [String] = Now.ToString("F") & " " & varLoggedInInits
footerSpace.Graphics.DrawString(footerText, font, PdfBrushes.Black, 0, y, Left_just)
'draw dynamic field in footer space
Dim number As New PdfPageNumberField()
Dim count As New PdfPageCountField()
Dim compositeField As New PdfCompositeField(font, PdfBrushes.Black, "Page {0} of {1} © Gymdata", number, count)
compositeField.StringFormat = New PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top)
Dim size As SizeF = font.MeasureString(compositeField.Text)
'compositeField.Bounds = New RectangleF(pageSize.Width - size.Width, y, size.Width, size.Height)
compositeField.Bounds = New RectangleF(pageSize.Width - (size.Width / 3), y, size.Width, size.Height)
compositeField.Draw(footerSpace.Graphics)
Return footerSpace
End Function
Shared Sub Do_It(ByRef thedata As DataTable, ByVal TheHeader As String, ByVal Filename As String)
Rept = New PdfDocument
Rept.PageSettings.Margins = New PdfMargins(0)
Dim unitCvtr As New PdfUnitConvertor()
themargin = New PdfMargins(20, 45, 20, 20)
If Portrait = True Then
Rept.PageSettings.Orientation = PdfPageOrientation.Portrait
page = Rept.Pages.Add(PdfPageSize.A4, themargin, PdfPageRotateAngle.RotateAngle0, PdfPageOrientation.Portrait)
Else
Rept.PageSettings.Orientation = PdfPageOrientation.Landscape
Rept.PageSettings.Rotate = PdfPageRotateAngle.RotateAngle90
page = Rept.Pages.Add(PdfPageSize.A4, themargin, PdfPageRotateAngle.RotateAngle0, PdfPageOrientation.Landscape)
End If
'page = Rept.Pages.Add(PdfPageSize.A4, themargin)
Rept.Template.Top = CreateHeaderTemplate(Rept, themargin, TheHeader)
Rept.Template.Bottom = CreateFooterTemplate(Rept, themargin)
' Rept.Template.Bottom = New PdfPageTemplateElement(Rept.PageSettings.Size.Width, themargin.Bottom)
'Rept.Template.Left = New PdfPageTemplateElement(themargin.Left, Rept.PageSettings.Size.Height)
'Rept.Template.Right = New PdfPageTemplateElement(themargin.Right, Rept.PageSettings.Size.Height)
Rept.Template.Left = New PdfPageTemplateElement(0, Rept.PageSettings.Size.Height)
Rept.Template.Right = New PdfPageTemplateElement(themargin.Right, Rept.PageSettings.Size.Height)
Rept.PageScaling = PdfPrintPageScaling.CustomSacle
PrintWidth = page.Canvas.ClientSize.Width
PrintHeight = page.Canvas.ClientSize.Height
NextYPosition = 55
Dim table As New PdfTable
table.Style.CellPadding = 3
table.Style.HeaderSource = PdfHeaderSource.ColumnCaptions
table.Style.HeaderRowCount = 1
table.DataSource = thedata
table.Style.ShowHeader = True
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.White
table.Style.HeaderStyle.Font = HeadFont
table.Style.HeaderStyle.StringFormat = New PdfStringFormat(PdfTextAlignment.Left)
table.Style.DefaultStyle.StringFormat = New PdfStringFormat(PdfTextAlignment.Left)
table.Style.HeaderStyle.TextBrush = PdfBrushes.Red
table.Style.HeaderStyle.BorderPen = New PdfPen(PdfBrushes.Black)
table.Style.DefaultStyle.BorderPen = New PdfPen(PdfBrushes.Blue)
table.Style.BorderPen = New PdfPen(PdfBrushes.Blue)
table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.White
table.Style.DefaultStyle.Font = BodyFont
Dim colno As Integer = -1
For Each column As PdfColumn In table.Columns
colno += 1
column.Width = CDec(col_tab.Rows(colno).Item("ColWidth").ToString())
If col_tab.Rows(colno).Item("ColType").ToString.StartsWith("Dec") Or col_tab.Rows(colno).Item("ColType").ToString.StartsWith("Int") Or col_tab.Rows(colno).Item("ColType").ToString.StartsWith("Mon") Then
column.StringFormat = New PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle)
column.ColumnName = col_tab.Rows(colno).Item("ColName").ToString ' .PadLeft(CInt(col_tab.Rows(colno).Item("ColWidth").ToString()))
'Column.StringFormat = New PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle)
End If
Next
Dim offset As Integer = 0
offset = CInt((Rept.PageSettings.Width - TableWidth - 20) / 2)
If TableWidth > Rept.PageSettings.Width Then
TableWidth = Rept.PageSettings.Width - 20
offset = 0
End If
'table.Draw(page, New PointF(offset, NextYPosition))
table.Draw(page, offset, NextYPosition, TableWidth)
Dim SaveLocation As String = varSoftwareDirectory & "\reports\" & Filename & "-" & Microsoft.VisualBasic.Format(Now.Year, "0000") & "-" & Microsoft.VisualBasic.Format(Now.Month, "00") & "-" & Microsoft.VisualBasic.Format(Now.Day, "00") & "-" & Microsoft.VisualBasic.Format(Now.Hour, "00") & Microsoft.VisualBasic.Format(Now.Minute, "00") & Microsoft.VisualBasic.Format(Now.Second, "00") & ".pdf"
Rept.SaveToFile(SaveLocation)
If Preview = True Then
Dim pdfDocumentViewer1 As PdfDocumentViewer = New PdfDocumentViewer
pdfDocumentViewer1.LoadFromFile(SaveLocation)
System.Diagnostics.Process.Start(SaveLocation)
Else
Dim pr_rep As New PdfDocument
pr_rep.LoadFromFile(SaveLocation)
pr_rep.PrintDocument.Print()
End If
End Sub
Shared Sub Extract_CSV(report_DT As DataTable, ByVal header As String)
If (Not System.IO.Directory.Exists(varSoftwareDirectory & "\extracts")) Then
System.IO.Directory.CreateDirectory(varSoftwareDirectory & "\extracts")
End If
Dim File_Name As String = varSoftwareDirectory & "\extracts\" & Format(Now(), "yyyyMMddHHmmss") & " " & Replace(header, "/", "-") & ".csv"
FileOpen(1, File_Name, OpenMode.Output, OpenAccess.Write, OpenShare.LockWrite)
Dim reportDetailsRow As DataRow
Dim colCount As Integer = report_DT.Columns.Count - 1
Dim rowCount As Integer = report_DT.Rows.Count - 1
'Headings on each column
For j = 0 To colCount
AddFieldToLine(report_DT.Columns(j).ColumnName)
Next j
DoCSVLineEnd()
For j = 0 To rowCount
reportDetailsRow = report_DT.Rows(j)
For x = 0 To colCount
If Not IsDBNull(reportDetailsRow.Item(x)) Then
AddFieldToLine(reportDetailsRow.Item(x).ToString)
Else
AddFieldToLine("")
End If
Next x
DoCSVLineEnd()
Next
FileClose(1)
MsgBox("Extract Complete to " & File_Name)
End Sub
Shared Sub AddFieldToLine(Field As String)
If CSVLine <> "" Then CSVLine &= ","
CSVLine &= Chr(34) & Trim(Field) & Chr(34)
End Sub
Shared Sub DoCSVLineEnd()
Print(1, CSVLine & Chr(13) & Chr(10))
CSVLine = ""
End Sub
End Class '......
Rept = New PdfDocument
Rept.PageSettings.Margins = New PdfMargins(0)
Dim unitCvtr As New PdfUnitConvertor()
themargin = New PdfMargins(20, 45, 20, 20)
'set the top margin to 0
Dim newThemargin As PdfMargins = New PdfMargins(themargin.Left, 0, themargin.Right, themargin.Bottom)
If Portrait = True Then
Rept.PageSettings.Orientation = PdfPageOrientation.Portrait
page = Rept.Pages.Add(PdfPageSize.A4, newThemargin, PdfPageRotateAngle.RotateAngle0, PdfPageOrientation.Portrait)
Else
Rept.PageSettings.Orientation = PdfPageOrientation.Landscape
Rept.PageSettings.Rotate = PdfPageRotateAngle.RotateAngle90
page = Rept.Pages.Add(PdfPageSize.A4, newThemargin, PdfPageRotateAngle.RotateAngle0, PdfPageOrientation.Landscape)
End If
'......