Public Sub CreatePDF(ByVal DesnationFilePath As String, _
ByVal SourceFiles As List(Of String), _
ByVal CropArea As Rectangle)
'Create a new PDF document
Dim OutputDoc As PdfSharp.Pdf.PdfDocument = New PdfSharp.Pdf.PdfDocument
OutputDoc.Info.Title = "Created with PDFsharp"
'Add one image or PDF at a time
For PageNumber As Integer = 0 To SourceFiles.Count - 1
Dim SourceFilePath As String = SourceFiles(PageNumber)
If LCase(IO.Path.GetExtension(SourceFilePath)) = ".pdf" Then
AddPdf(OutputDoc, SourceFilePath, CropArea)
Else 'Must be a picture
AddPicture(OutputDoc, SourceFilePath, CropArea)
End If
Next
'Save
OutputDoc.Save(DesnationFilePath)
End Sub
Private Sub AddPicture(ByRef OutputDoc As PdfSharp.Pdf.PdfDocument, ByVal ImgPath As String, ByVal CropArea As Rectangle)
'Create an empty page
Dim page As PdfSharp.Pdf.PdfPage = OutputDoc.AddPage()
'Draw image
Dim gfx As PdfSharp.Drawing.XGraphics = PdfSharp.Drawing.XGraphics.FromPdfPage(page)
Dim image As PdfSharp.Drawing.XImage
If CropArea = Nothing Then
Dim SourceImg As System.Drawing.Bitmap = Bitmap.FromFile(ImgPath)
image = PdfSharp.Drawing.XImage.FromGdiPlusImage(SourceImg)
Else
Dim OriginalImage As Bitmap = Bitmap.FromFile(ImgPath)
Dim CroppedImage As Image = OriginalImage.Clone(CropArea, OriginalImage.PixelFormat)
image = PdfSharp.Drawing.XImage.FromGdiPlusImage(CroppedImage)
End If
page.Height = (image.PixelHeight * 0.0025) * 72.0 * 400.0 / image.VerticalResolution
page.Width = (image.PixelWidth * 0.0025) * 72.0 * 400.0 / image.HorizontalResolution
gfx.DrawImage(image, 0, 0)
End Sub
Private Sub AddPdf(ByRef OutputDoc As PdfSharp.Pdf.PdfDocument, ByVal PdfPath As String, ByVal CropArea As Rectangle)
'Add one page at a time
Dim InputDoc As PdfSharp.Pdf.PdfDocument = PdfSharp.Pdf.IO.PdfReader.Open(PdfPath, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import)
For i As Integer = 0 To InputDoc.PageCount - 1
OutputDoc.AddPage(InputDoc.Pages(i))
Next
End Sub