VB.Net Merge multiple pdfs into one and export - vb.net

I have to merge multiple PDFs into a single PDF.
I am using the iText.sharp library, and collect converted the code and tried to use it (from here)
The actual code is in C# and I converted that to VB.NET.
Private Function MergeFiles(ByVal sourceFiles As List(Of Byte())) As Byte()
Dim mergedPdf As Byte() = Nothing
Using ms As New MemoryStream()
Using document As New Document()
Using copy As New PdfCopy(document, ms)
document.Open()
For i As Integer = 0 To sourceFiles.Count - 1
Dim reader As New PdfReader(sourceFiles(i))
' loop over the pages in that document
Dim n As Integer = reader.NumberOfPages
Dim page As Integer = 0
While page < n
page = page + 1
copy.AddPage(copy.GetImportedPage(reader, page))
End While
Next
End Using
End Using
mergedPdf = ms.ToArray()
End Using
End Function
I am now getting the following error:
An item with the same key has already been added.
I did some debugging and have tracked the problem down to the following lines:
copy.AddPage(copy.GetImportedPage(reader,
copy.AddPage(copy.GetImportedPage(reader, page)))
Why is this error happening?

I have a console that monitors individual folders in a designated folder then needs to merge all of the pdf's in that folder into a single pdf. I pass an array of file paths as strings and the output file i would like.
This is the function i use.
Public Shared Function MergePdfFiles(ByVal pdfFiles() As String, ByVal outputPath As String) As Boolean
Dim result As Boolean = False
Dim pdfCount As Integer = 0 'total input pdf file count
Dim f As Integer = 0 'pointer to current input pdf file
Dim fileName As String
Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
Dim pageCount As Integer = 0
Dim pdfDoc As iTextSharp.text.Document = Nothing 'the output pdf document
Dim writer As PdfWriter = Nothing
Dim cb As PdfContentByte = Nothing
Dim page As PdfImportedPage = Nothing
Dim rotation As Integer = 0
Try
pdfCount = pdfFiles.Length
If pdfCount > 1 Then
'Open the 1st item in the array PDFFiles
fileName = pdfFiles(f)
reader = New iTextSharp.text.pdf.PdfReader(fileName)
'Get page count
pageCount = reader.NumberOfPages
pdfDoc = New iTextSharp.text.Document(reader.GetPageSizeWithRotation(1), 18, 18, 18, 18)
writer = PdfWriter.GetInstance(pdfDoc, New FileStream(outputPath, FileMode.OpenOrCreate))
With pdfDoc
.Open()
End With
'Instantiate a PdfContentByte object
cb = writer.DirectContent
'Now loop thru the input pdfs
While f < pdfCount
'Declare a page counter variable
Dim i As Integer = 0
'Loop thru the current input pdf's pages starting at page 1
While i < pageCount
i += 1
'Get the input page size
pdfDoc.SetPageSize(reader.GetPageSizeWithRotation(i))
'Create a new page on the output document
pdfDoc.NewPage()
'If it is the 1st page, we add bookmarks to the page
'Now we get the imported page
page = writer.GetImportedPage(reader, i)
'Read the imported page's rotation
rotation = reader.GetPageRotation(i)
'Then add the imported page to the PdfContentByte object as a template based on the page's rotation
If rotation = 90 Then
cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height)
ElseIf rotation = 270 Then
cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, reader.GetPageSizeWithRotation(i).Width + 60, -30)
Else
cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0)
End If
End While
'Increment f and read the next input pdf file
f += 1
If f < pdfCount Then
fileName = pdfFiles(f)
reader = New iTextSharp.text.pdf.PdfReader(fileName)
pageCount = reader.NumberOfPages
End If
End While
'When all done, we close the document so that the pdfwriter object can write it to the output file
pdfDoc.Close()
result = True
End If
Catch ex As Exception
Return False
End Try
Return result
End Function

the code that was marked correct does not close all the file streams therefore the files stay open within the app and you wont be able to delete unused PDFs within your project
This is a better solution:
Public Sub MergePDFFiles(ByVal outPutPDF As String)
Dim StartPath As String = FileArray(0) ' this is a List Array declared Globally
Dim document = New Document()
Dim outFile = Path.Combine(outPutPDF)' The outPutPDF varable is passed from another sub this is the output path
Dim writer = New PdfCopy(document, New FileStream(outFile, FileMode.Create))
Try
document.Open()
For Each fileName As String In FileArray
Dim reader = New PdfReader(Path.Combine(StartPath, fileName))
For i As Integer = 1 To reader.NumberOfPages
Dim page = writer.GetImportedPage(reader, i)
writer.AddPage(page)
Next i
reader.Close()
Next
writer.Close()
document.Close()
Catch ex As Exception
'catch a Exception if needed
Finally
writer.Close()
document.Close()
End Try
End Sub

I realize I'm pretty late to the party, but after reading the comments from #BrunoLowagie, I wanted to see if I could put something together myself that uses the examples from his linked sample chapter. It's probably overkill, but I put together some code that merges multiple PDFs into a single file that I posted on the Code Review SE site (the post, VB.NET - Error Handling in Generic Class for PDF Merge, contains the full class code). It only merges PDF files right now, but I'm planning on adding methods for additional functionality later.
The "master" method (towards the end of the Class block in the linked post, and also posted below for reference) handles the actual merging of the PDF files, but the multiple overloads provide a number of options for how to define the list of original files. So far, I've included the following features:
The methods return a System.IO.FileInfo object if the merge is successful.
Provide a System.IO.DirectoryInfo object or a System.String identifying a path and it will collect all PDF files in that directory (including sub-directories if specified) to merge.
Provide a List(Of System.String) or a List(Of System.IO.FileInfo) specifying the PDFs you want to merge.
Identify how the PDFs should be sorted before the merge (especially useful if you use one of the MergeAll methods to get all PDF files in a directory).
If the specified output PDF file already exists, you can specify whether or not you want to overwrite it. (I'm considering adding the "ability" to automatically adjust the output PDF file's name if it already exists).
Warning and Error properties provide a way to get feedback in the calling method, whether or not the merge is successful.
Once the code is in place, it can be used like this:
Dim PDFDir As New IO.DirectoryInfo("C:\Test Data\PDF\")
Dim ResultFile As IO.FileInfo = Nothing
Dim Merger As New PDFManipulator
ResultFile = Merger.MergeAll(PDFDir, "C:\Test Data\PDF\Merged.pdf", True, PDFManipulator.PDFMergeSortOrder.FileName, True)
Here is the "master" method. As I said, it's probably overkill (and I'm still tweaking it some), but I wanted to do my best to try to make it work as effectively as possible. Obviously it requires a Reference to the itextsharp.dll for access to the library's functions.
I've commented out the references to the Error and Warning properties of the class for this post to help reduce any confusion.
Public Function Merge(ByVal PDFFiles As List(Of System.IO.FileInfo), ByVal OutputFileName As String, ByVal OverwriteExistingPDF As Boolean, ByVal SortOrder As PDFMergeSortOrder) As System.IO.FileInfo
Dim ResultFile As System.IO.FileInfo = Nothing
Dim ContinueMerge As Boolean = True
If OverwriteExistingPDF Then
If System.IO.File.Exists(OutputFileName) Then
Try
System.IO.File.Delete(OutputFileName)
Catch ex As Exception
ContinueMerge = False
'If Errors Is Nothing Then
' Errors = New List(Of String)
'End If
'Errors.Add("Could not delete existing output file.")
Throw
End Try
End If
End If
If ContinueMerge Then
Dim OutputPDF As iTextSharp.text.Document = Nothing
Dim Copier As iTextSharp.text.pdf.PdfCopy = Nothing
Dim PDFStream As System.IO.FileStream = Nothing
Dim SortedList As New List(Of System.IO.FileInfo)
Try
Select Case SortOrder
Case PDFMergeSortOrder.Original
SortedList = PDFFiles
Case PDFMergeSortOrder.FileDate
SortedList = PDFFiles.OrderBy(Function(f As System.IO.FileInfo) f.LastWriteTime).ToList
Case PDFMergeSortOrder.FileName
SortedList = PDFFiles.OrderBy(Function(f As System.IO.FileInfo) f.Name).ToList
Case PDFMergeSortOrder.FileNameWithDirectory
SortedList = PDFFiles.OrderBy(Function(f As System.IO.FileInfo) f.FullName).ToList
End Select
If Not IO.Directory.Exists(New IO.FileInfo(OutputFileName).DirectoryName) Then
Try
IO.Directory.CreateDirectory(New IO.FileInfo(OutputFileName).DirectoryName)
Catch ex As Exception
ContinueMerge = False
'If Errors Is Nothing Then
' Errors = New List(Of String)
'End If
'Errors.Add("Could not create output directory.")
Throw
End Try
End If
If ContinueMerge Then
OutputPDF = New iTextSharp.text.Document
PDFStream = New System.IO.FileStream(OutputFileName, System.IO.FileMode.OpenOrCreate)
Copier = New iTextSharp.text.pdf.PdfCopy(OutputPDF, PDFStream)
OutputPDF.Open()
For Each PDF As System.IO.FileInfo In SortedList
If ContinueMerge Then
Dim InputReader As iTextSharp.text.pdf.PdfReader = Nothing
Try
InputReader = New iTextSharp.text.pdf.PdfReader(PDF.FullName)
For page As Integer = 1 To InputReader.NumberOfPages
Copier.AddPage(Copier.GetImportedPage(InputReader, page))
Next page
If InputReader.IsRebuilt Then
'If Warnings Is Nothing Then
' Warnings = New List(Of String)
'End If
'Warnings.Add("Damaged PDF: " & PDF.FullName & " repaired and successfully merged into output file.")
End If
Catch InvalidEx As iTextSharp.text.exceptions.InvalidPdfException
'Skip this file
'If Errors Is Nothing Then
' Errors = New List(Of String)
'End If
'Errors.Add("Invalid PDF: " & PDF.FullName & " not merged into output file.")
Catch FormatEx As iTextSharp.text.pdf.BadPdfFormatException
'Skip this file
'If Errors Is Nothing Then
' Errors = New List(Of String)
'End If
'Errors.Add("Bad PDF Format: " & PDF.FullName & " not merged into output file.")
Catch PassworddEx As iTextSharp.text.exceptions.BadPasswordException
'Skip this file
'If Errors Is Nothing Then
' Errors = New List(Of String)
'End If
'Errors.Add("Password-protected PDF: " & PDF.FullName & " not merged into output file.")
Catch OtherEx As Exception
ContinueMerge = False
Finally
If Not InputReader Is Nothing Then
InputReader.Close()
InputReader.Dispose()
End If
End Try
End If
Next PDF
End If
Catch ex As iTextSharp.text.pdf.PdfException
ResultFile = Nothing
ContinueMerge = False
'If Errors Is Nothing Then
' Errors = New List(Of String)
'End If
'Errors.Add("iTextSharp Error: " & ex.Message)
If System.IO.File.Exists(OutputFileName) Then
If Not OutputPDF Is Nothing Then
OutputPDF.Close()
OutputPDF.Dispose()
End If
If Not PDFStream Is Nothing Then
PDFStream.Close()
PDFStream.Dispose()
End If
If Not Copier Is Nothing Then
Copier.Close()
Copier.Dispose()
End If
System.IO.File.Delete(OutputFileName)
End If
Throw
Catch other As Exception
ResultFile = Nothing
ContinueMerge = False
'If Errors Is Nothing Then
' Errors = New List(Of String)
'End If
'Errors.Add("General Error: " & other.Message)
If System.IO.File.Exists(OutputFileName) Then
If Not OutputPDF Is Nothing Then
OutputPDF.Close()
OutputPDF.Dispose()
End If
If Not PDFStream Is Nothing Then
PDFStream.Close()
PDFStream.Dispose()
End If
If Not Copier Is Nothing Then
Copier.Close()
Copier.Dispose()
End If
System.IO.File.Delete(OutputFileName)
End If
Throw
Finally
If Not OutputPDF Is Nothing Then
OutputPDF.Close()
OutputPDF.Dispose()
End If
If Not PDFStream Is Nothing Then
PDFStream.Close()
PDFStream.Dispose()
End If
If Not Copier Is Nothing Then
Copier.Close()
Copier.Dispose()
End If
If System.IO.File.Exists(OutputFileName) Then
If ContinueMerge Then
ResultFile = New System.IO.FileInfo(OutputFileName)
If ResultFile.Length <= 0 Then
ResultFile = Nothing
Try
System.IO.File.Delete(OutputFileName)
Catch ex As Exception
Throw
End Try
End If
Else
ResultFile = Nothing
Try
System.IO.File.Delete(OutputFileName)
Catch ex As Exception
Throw
End Try
End If
Else
ResultFile = Nothing
End If
End Try
End If
Return ResultFile
End Function

Some may have to make a change to the code at "writer = PdfWriter.GetInstance(pdfDoc, New FileStream(outputPath, FileMode.OpenOrCreate))" as iTextSharp may not support
Change to:
Dim fs As IO.FileStream = New IO.FileStream(outputPath, IO.FileMode.Create)
writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, fs)

Related

Google Drive API v3 VB.NET Upload To Spesific Folder

Please Help, i'm trying to upload file to specific folder in my google drive using Vb.net. but, i'm googling for hours and not get working code. i cant sleep because this. here is my code:
Private Sub UploadFile(FilePath As String)
Try
If Service.ApplicationName <> "Google Drive VB Dot Net" Then CreateService()
Dim TheFile As New File()
TheFile.Name = "Database Sekretariat.accdb"
TheFile.Description = "A test document"
'TheFile.MimeType = "text/plain"
TheFile.Parents(0) = "1uMeTMRtvhm5_98udPmV8kp19aGtrmeQj"
Dim ByteArray As Byte() = System.IO.File.ReadAllBytes(FilePath)
Dim Stream As New System.IO.MemoryStream(ByteArray)
Dim UploadRequest As FilesResource.CreateMediaUpload = Service.Files.Create(TheFile, Stream, TheFile.MimeType)
UploadRequest.Upload()
Dim file As File = UploadRequest.ResponseBody
MsgBox("Upload Selesai " & file.Name & "")
Catch ex As Exception
MsgBox("Upload Gagal")
End Try
End Sub
use it in the following way, it is functional
First, i look for the ID folder
Public Sub SearchFolder()
IDFolderSave = String.Empty 'Global Variable
Try
Dim findrequest As FilesResource.ListRequest = Service.Files.List
Dim listFolder As Data.FileList = findrequest.Execute
For Each item As File In listFolder.Files
If item.MimeType = "application/vnd.google-apps.folder" Then
If item.Name = "NameFolder" Then
IDFolderSave = item.Id.ToString
Exit For
End If
End If
Next
Catch ex As Exception
Throw ex
End Try
'MsgBox("Folder id: " + idFolder)
End Sub
Second, upload file
Public Sub UploadFileInFolder()
Dim FilePath As String = String.Empty
FilePath = "C:\Icons\Loadding.gif"
Dim plist As List(Of String) = New List(Of String)
SearchFolder()
plist.Add(IDFolderSave) 'Set parent folder
If (System.IO.File.Exists(FilePath)) Then
Dim fileMetadata = New File() With {
.Name = "Test",
.Parents = plist
}
Dim request As FilesResource.CreateMediaUpload
Using stream = New System.IO.FileStream(FilePath, System.IO.FileMode.Open)
request = Service.Files.Create(fileMetadata, stream, "application/octet-stream")
request.Fields = "id, parents"
request.Upload()
End Using
Dim file As File = request.ResponseBody
IDFileShared = file.Id
SharedFile()
MsgBox("File upload: " + file.Id)
Else
MsgBox("File does not exist: " + FilePath)
End If
End Sub
I hope it helps you

IDE thinks I need to close a loop but it looks fine to me

IDE says the Next for the
for i
right below the "Loop through folders commentis missing.
Here is my code.
Dim strVal As String
'Loop through Folders
For i As Integer = 0 To lbFolder.Items.Count - 1
Dim iText As String = CStr(lbFolder.Items(i))
Dim partPath As String = lblPath.Text + "\" + iText
Dim pathNum As String = partPath + "\1900\"
Dim directory As New DirectoryInfo(pathNum)
Dim fileArr As FileInfo() = directory.GetFiles() ' Get a reference to each file in that directory.
' Display the names of the files.
Dim xItem As FileInfo
'loop through files
For Each xItem In fileArr ' add to listbox
lblFname.Text = xItem.ToString
strVal = pathNum & xItem.ToString
lbFiles.Items.Add(strVal)
Next
For j = 0 To lbFiles.Items.Count - 1 'read through files listbox
Dim FileID, Sequence, Time, Lat, Longitude, Average, Channel As String
'declaration of filestream to open file
Dim sr As StreamReader
'filestream object to open and read file
Dim fs As FileStream
Try
'clearing listbox data toavoid confusion
ListView1.Items.Clear()
fs = New FileStream((lbFiles.Items.Item(j)), FileMode.OpenOrCreate)
'stream reader object to read streamed input
sr = New StreamReader(fs)
Dim itm As Object
'reading line by line
itm = sr.ReadLine
While Not itm = Nothing
Dim split As String() = itm.Split(New [Char]() {","})
FileID = split(0)
Sequence = split(1)
Time = split(2)
Lat = split(3)
Longitude = split(4)
Average = split(5)
Channel = split(6)
With ListView1
.Items.Add(FileID)
.Items(ListView1.Items.Count - 1).SubItems.Add(Sequence)
.Items(ListView1.Items.Count - 1).SubItems.Add(Time)
.Items(ListView1.Items.Count - 1).SubItems.Add(Lat)
.Items(ListView1.Items.Count - 1).SubItems.Add(Longitude)
.Items(ListView1.Items.Count - 1).SubItems.Add(Average)
.Items(ListView1.Items.Count - 1).SubItems.Add(Channel)
End With
itm = sr.ReadLine
End While
'close stream reader and filestrema object
sr.Close()
fs.Close()
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message, "Load Tool Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Next j
lbFiles.Items.Clear()
Next i
End Sub
I am using visual studio, when I click on the for i it shows the closing next but when I run I get an error.
What am I missing?
Add **xItem** after the Next
For Each xItem In fileArr ' add to listbox
lblFname.Text = xItem.ToString
strVal = pathNum & xItem.ToString
lbFiles.Items.Add(strVal)
Next xItem
Restarted the IDE and everything ran with no errors.
Thanks all who responded

Storing a selected notepad its contents to FileStream

I am currently having problems in storing the contents of any selected notepad file from openFileDialog to the FileStream. My code states a default filename as i do not know how to revise the FileStream code, i want it to register the filename of my selected notepad.
By default it would only read the contents of "messages.txt", i want to have a freedom to choose any notepad file and retrieve the data from it. Any kind of help or advice will do thanks in advance.
here is my code:
Dim Stream As New System.IO.FileStream("messages.txt", IO.FileMode.Open)
'i need to do something about this line above
Dim sReader As New System.IO.StreamReader(Stream)
Dim Index As Integer = 0
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "D:\work"
openFileDialog1.Filter = "txt files (*.txt)|*.txt"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
Stream = openFileDialog1.OpenFile()
If (Stream IsNot Nothing) Then
Do While sReader.Peek >= 0
ReDim Preserve eArray(Index)
eArray(Index) = sReader.ReadLine
RichTextBox3.Text = eArray(Index)
Index += 1
Delay(2)
Loop
End If
Catch Ex As Exception
MessageBox.Show(Ex.Message)
Finally
If (Stream IsNot Nothing) Then
Stream.Close()
End If
End Try
End If
End Sub
I rearranged your code just a bit. Basically you were creating a stream, and then creating the reader for the stream to "messages.txt". Later you set the stream object to a new stream based on the OpenFile method of the file open dialog. But your reader was still pointing to the first stream you opened, so that is what was getting read. I've changed the code below to not open that first stream, and to create the reader after you have created the stream based on the file the user selected.
'don't create a stream hear and the reader, because you are just recreating a stream later in the code
Dim Stream As System.IO.FileStream
Dim Index As Integer = 0
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "D:\work"
openFileDialog1.Filter = "txt files (*.txt)|*.txt"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
'This line opens the file the user selected and sets the stream object
Stream = openFileDialog1.OpenFile()
If (Stream IsNot Nothing) Then
'create the reader here and use the stream you got from the file open dialog
Dim sReader As New System.IO.StreamReader(Stream)
Do While sReader.Peek >= 0
ReDim Preserve eArray(Index)
eArray(Index) = sReader.ReadLine
RichTextBox3.Text = eArray(Index)
Index += 1
Delay(2)
Loop
End If
Catch Ex As Exception
MessageBox.Show(Ex.Message)
Finally
If (Stream IsNot Nothing) Then
Stream.Close()
End If
End Try
End If
End Sub

Save file if error reading with Stream Reader

I am trying to parse a uploaded txt file. I need to save the file if there is an error parsing it. The problem is that the parser is using a Stream Reader and if an error occurs it just saves the empty file and not the file contents.
Dim file As HttpPostedFile = context.Request.Files(0)
If Not IsNothing(file) AndAlso file.ContentLength > 0 AndAlso Path.GetExtension(file.FileName) = ".txt" Then
Dim id As Integer = (Int32.Parse(context.Request("id")))
Try
ParseFile(file, id)
context.Response.Write("success")
Catch ex As Exception
Dim filename As String = file.FileName
Dim uploadPath = context.Server.MapPath("~/Errors/MyStudentDataFiles/")
file.SaveAs(uploadPath + id.ToString() + filename)
End Try
Else
context.Response.Write("error")
End If
My ParseFile method is something like this
Protected Sub ParseFile(ByVal studentLoanfile As HttpPostedFile, ByVal id As Integer)
Using r As New StreamReader(studentLoanfile.InputStream)
line = GetLine(r)
End Using
End Sub
Is there a way to Clone the file before it gets passed into the parseFile sub or a way to read the file without loosing the contents?
Thanks in advance
For anyone who runs into this problem in the future, I ended up reading the file to the end and saving it into a variable. Then converted it back into a memory stream to use for the parser. If an error occurs, I just create a new file with the string. This is the code I used.
Dim id As Integer = (Int32.Parse(context.Request("id")))
'Read full file for error logging
Dim content As String = [String].Empty
Using sr = New StreamReader(uploadedFile.InputStream)
content = sr.ReadToEnd()
End Using
'Convert it back into a stream
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(content)
Dim stream As New MemoryStream(byteArray)
Try
ParseFile(stream, id, content)
context.Response.Write("success")
Catch ex As Exception
Dim filename As String = uploadedFile.FileName
Dim uploadPath = context.Server.MapPath("~/Errors/MyStudentDataFiles/")
'Save full file on error
Using sw As StreamWriter = File.CreateText(uploadPath + id.ToString() + filename)
sw.WriteLine(content)
End Using
context.Response.Write("error")
Throw ex
End Try
Else
context.Response.Write("error")
End If

Pdf to Tiff file covert in vb.net using PdfSharp.dll

i am using Pdfsharp.dll to convert tiff image to pdf file in vb.net, and it is successfull when i run in my machine, when i use it from other machine, which shows the Error like "Raw string contains invalid character with a value > 255.", please any one help me to fix error,
i using the PdfSharp.dll library and the following code
Dim objDoc As PdfDocument
Dim objPdfPage As PdfPage
Dim objTiffImg As Image
Dim objXImg As XImage
Dim iPageCount As Integer
Dim objXgr As XGraphics
Dim sPdfFile As String = Nothing
Dim objDir As DirectoryInfo
Dim objFile As FileInfo()
Dim objFileInfo As FileInfo
Try
objTiffImageSpliter = New TiffImageSplitter()
objDoc = New PdfDocument
iPageCount = objTiffImageSpliter.GetPageCount(sFileName)
For iCount As Integer = 0 To iPageCount - 1
objPdfPage = New PdfPage
objTiffImg = objTiffImageSpliter.getTiffImage(sFileName, iCount)
objXImg = XImage.FromGdiPlusImage(objTiffImg)
'objPdfPage.Height = objXImg.PointWidth
'objPdfPage.Width = objXImg.PointHeight
objDoc.Pages.Add(objPdfPage)
objXgr = XGraphics.FromPdfPage(objDoc.Pages(iCount))
objXgr.DrawImage(objXImg, 10, 10)
Next
sPdfFile = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\MY_FaxFile\"
If System.IO.Directory.Exists(sPdfFile) Then
objDir = New DirectoryInfo(sPdfFile)
objFile = objDir.GetFiles()
For Each objFileInfo In objFile
objFileInfo.Delete()
Next
sPdfFile &= "MyFax.pdf"
Else
System.IO.Directory.CreateDirectory(sPdfFile)
sPdfFile &= "MyFax.pdf"
End If
objDoc.Save(sPdfFile) ' This Line shows the Error.
objDoc.Close()
Catch ex As Exception
MsgBox(ex.ToString)
sPdfFile = Nothing
End Try
Return sPdfFile
I'm not familiar with this library, but based on your code and error message, I would guess that your App Data folder contains non-ASCII characters and that the PdfSharp library does not support non-ASCII characters in the filename.