Using Spire.PDF to merge pdf files Errors - vb.net

I am using the free licenced version of Spire PDF. My program has in the region of 166,ooo pdf files which represent individual pages. I need to merge between 1 and 20 of these with the same names into one pdf.
I have a routine the builds a string of filenames to be added to an array which is passed to the following sub as PDFFiles. The OutputFile is the string with the name of the output file with it's path.
Private Sub MergePDFs(ByVal PDFFiles As String, ByVal OutPutFile As String)
Dim files As [String]() = New [String]() {"E:\Ballads of the 20th Century\1st bari #1.pdf", "E:\Ballads of the 20th Century\1st bari #2.pdf"}
Dim i As Integer
'open pdf documents
Dim docs As PdfDocument() = New PdfDocument(files.Length - 1) {}
For i = 0 To files.Length - 1
docs(i) = New PdfDocument(files(i))
Next
'append document
docs(0).AppendPage(docs(1))
'import PDF pages
i = 0
While i < docs(2).Pages.Count
docs(0).InsertPage(docs(2), i)
i = i + 2
End While
End Sub
I have the Solution Explorer I have the Spire.Pdf.dll as a file. In References I have Spire.Pdf and Spire.Licence.
At runtime I get An unhandled exception of type 'System.ArgumentException' occurred in Spire.Pdf.dll
Additional information: File doesn't exist.
The PDFFiles is not used in this example for clarity. The two files listed are taken directly from the program output for testing purposes.
There has to be a simple explanation for this error, but I haven't found one yet.
Please can you help solve it.
Thanks
Graham

I found the answer to this myself.
The actual problem was the way Spire.pdf parses a string into a pdf document.
There must be no spaces in the filename, then it works fine.
Graham

Related

vb.net How to save File as Word & Open Office Document?

I have a small programm and i want to save the File so i can read them later into when i open it.
How can i now save the File cause i must save 5 Variables and read them back into the Tool and if its possible i want to use the File in Word or OpenOffice too.
My Variables
Title - Pieces- SinglePrice- Totalprice
Please give me Examples for the Point in the right way.
Thanks everyone!
If all you want to do is store four variables from your program in a file that can also be read by Word and OpenOffice, you can do that easily enough with a text file. The following code assumes that Title is a String, Pieces is an Integer, SinglePrice and TotalPrice are Decimal.
Dim folder As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim saveFile As String = System.IO.Path.Combine(folder, "Save.txt")
Dim vars() As String = {Title, Pieces.ToString, SinglePrice.ToString, TotalPrice.ToString}
System.IO.File.WriteAllLines(saveFile, vars)
If you need to read the file to restore the values of the variables, you can do it like this. Note that this code assumes that the file was written by the first snippet of code, otherwise it would be necessary to validate the contaents of the file before using it.
Dim folder As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim saveFile As String = System.IO.Path.Combine(folder, "Save.txt")
Dim vars() As String = System.IO.File.ReadAllLines(saveFile)
Title = vars(0)
Pieces = CInt(vars(1))
SinglePrice = CDec(vars(2))
TotalPrice = CDec(vars(3))

GZipstream cuts off data from original file when decompressing

For a long time I have been trying to debug why my parsing counts were off when downloading files to be parsed and been made to look really dumb about this. I did some debugging and found that the file I download when trying to decompress using GZipStream shows that it misses data from the original file. Here is my code for decompressing:
Using originalFileStream As FileStream = fileItem.OpenRead()
Dim currentFileName As String = fileItem.FullName
Dim newFileName = currentFileName.Remove(currentFileName.Length - fileItem.Extension.Length)
newFile = newFileName
Using decompressedFileStream As FileStream = File.Create(newFileName)
Using decompressionStream As GZipStream = New GZipStream(originalFileStream, CompressionMode.Decompress)
decompressionStream.CopyTo(decompressedFileStream)
Console.WriteLine("Decompressed: {0}", fileItem.Name)
decompressionStream.Close()
originalFileStream.Close()
End Using
End Using
End Using
Now what I do is return the newfile to the calling function and read the contents from there:
Dim responseData As String = inputFile.ReadToEnd
Now pasting the url in the browser and downloading from there and then opening using winrar I can see the data is not the same. Now this does not happen all the time as some files parse and decompress correctly. Each downloaded file has check counter to compare how many posts I am supposed to be parsing from it and that triggered me to see the mismatch in counts.
EDIT
Here is what I found in addition. If I read the problem file (as I said that only some files happen this way) by individual lines I will get all the data:
Dim rData As String = inputFile.ReadLine
If Not rData = "" Then
While Not inputFile.EndOfStream
rData = inputFile.ReadLine + vbNewLine + rData
End While
getIndividualPosts(rData)
End If
Now if I try to read an individual line from a file that is not problematic it will return nothing and so I will have to readtoEnd. Can anyone explain this odd behavior and is it related to the GZIPSTREAM or some error in my code.

Stream Reader and Writer Conflict

I am making a class that is to help with saving some strings to a local text file (I want to append them to that file and not overwrite so that it is a log file). When I write with the streamwriter to find the end of the previous text, I get an error "the file is not available as it is being used by another process". I looked into this problem on MSDN and I got very little help. I tried to eliminate some variables so I removed the streamreader to check was that the problem and it was. When I tried to write to the file then it worked and I got no error so this made me come to the conclusion that the problem arose in the streamreader. But I could not figure out why?
Here is the code:
Public Sub SaveFile(ByVal Task As String, ByVal Difficulty As Integer, ByVal Time_Taken As String)
Dim SW As String = "C:/Program Files/Business Elements/Dashboard System Files/UserWorkEthic.txt"
Dim i As Integer
Dim aryText(3) As String
aryText(0) = Task
aryText(1) = Difficulty
aryText(2) = Time_Taken
Dim objWriter As System.IO.StreamWriter = New System.IO.StreamWriter(SW, True)
Dim reader As System.IO.StreamReader = New System.IO.StreamReader(SW, True)
reader.ReadToEnd()
reader.EndOfStream.ToString()
For i = 0 To 3
objWriter.WriteLine(aryText(reader.EndOfStream + i))
Next
reader.Close()
objWriter.Close()
End Sub
As Joel has commented on the previous answer it is possible to change the type of locking.
Otherwise building on what Neil has suggested, if to try to write to a file with a new reader it is difficult not to lose the information already within the file.
I would suggest you rename the original file to a temporary name, "UserWorkEthicTEMP.txt" for example. Create a new text file with the original name. Now; read a line, write a line, between the two files, before adding your new data onto the end. Finally Delete the temporary file and you will have the new file with the new details. If you have an error the temporary file will serve as a backup of the original. Some sample code below:
Change file names
Dim Line as string
line=Reader.readline
Do until Line=nothing
objwriter.writeline(line)
line=reader.readline
loop
add new values on the end and remove old file
You are trying to read and write to the same file and this is causing a lock contention. Either store the contents of the file into a variable and then write it back out including your new data to the file.
Psuedo
Reader.Open file
String content = Reader.ReadToEnd()
Reader.Close
Writer.Open file
Loop
Writer.Write newContent
Writer.Close

How to get the file name of a file in VB?

I make a search program for searching a list of files in a computer and then copy the file into a store folder. The file name could be "*11*2.txt" As long as the program find this pattern, it should copy to the store folder. The problem is that I don't know the exactly name of the file before the search and I don't want to rename the file, I don't know how to save the file. Please help
I use the following to find the file, which does its work
Public Sub DirSearch(ByVal sDir As String, ByVal FileName As String)
Dim To_Path As String
To_Path = Form1.TextBox5.Text
For Each foundFile As String In My.Computer.FileSystem.GetFiles(sDir, FileIO.SearchOption.SearchAllSubDirectories, FileName)
Copy2Local(foundFile, To_Path)
Next
End Sub
Here is the current version of the Copy2Local (Note: it is not working right)
Public Sub Copy2Local(ByVal Copy_From_Path As String, ByVal Copy_To_Path As String)
' Specify the directories you want to manipulate.
Try
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
' Copy the file.
File.Copy(Copy_From_Path, Copy_To_Path)
Catch
End Try
End Sub
First, you should check if ToPath is a valid directory since it's coming from a TextBox:
Dim isValidDir = Directory.Exists(ToPath)
Second, you can use Path.Combine to create a path from separate (sub)directories or file-names:
Dim copyToDir = Path.GetDirectoryName(Copy_To_Path)
Dim file = Path.GetFileName(Copy_From_Path)
Dim newPath = Path.Combine(copyToDir, file)
http://msdn.microsoft.com/en-us/library/system.io.path.aspx
(disclaimer: typed from a mobile)
To answer your question: You can get the file name with Path.GetFileName. Example:
Dim fileName As String = Path.GetFileName(foundFile)
However, there's a bunch of other things wrong with your code:
Here,
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
you are overwriting your source file. This does not seem like a good idea. ;-)
And here,
Try
...
Catch
' Do Nothing
End Try
You are throwing away exceptions that would help you find and diagnose problems. Don't do that. It makes debugging a nightmare.
In vb.net, I'm using the following code to find the filename
Textbox1.Text = New FileInfo(OpenFileDialog.FileName).Name
this code work fine with open file dialog box

VB.NET Renaming File and Retagging / Edit Image MetaData / Meta Tags

Clarifiration:
How do I Edit and Save Image EXIF / Metadata / FileInfo without using an external DLL?
Project:
I'm building an app for personal use to rename, retag, and organize the apocalyptic quantity of images I host on my personal website. As I have been collecting funny pictures and such for several years, there is no real rhyme or reason to the file naming conventions. Ergo, Image0001.jpg needs to be renamed to a descriptive filename, and the Metadata fields need to be filled in.
The desired process will take an existing jpg, gif, png, tiff or bmp and do the following:
load image into memory
convert bmp files to jpgs if needed (for a smaller file size, mostly)
load image tags into ImageData Structure (see below)
load file data into ImageData Structure (where needed)
display image and tags for user to edit (In a Picture Box and several Text Boxes)
allow editing of fields and renaming of the file
write the changes to the image file
go to next file.
Example:
Load Image0001.jpg. Populate ImageData Structure fields.
Type in Description: "lolcat ceiling cat sends son".
ImageData.FileName changed to "lolcat-ceiling-cat-sends-son.jpg".
ImageData.Name, .Keywords, .Title, .Subject, and .Comments changed to "lolcat ceiling cat sends son".
Save file with new filename and save all new tag fields.
(Later, I will also be using SQL to build a referential database with links to the online copies of these files to allow for searching by keywords, subject, filename, etc, but that's another layer that's much easier than this one. At least to me.)
Problem:
So far, several days of research have yielded almost no measurable progress. Information has apparently been inexplicably hidden behind a bunch of unexpected search keywords that I have not though to use for my searches. Any help would be appreciated.
Current Code as is:
Imports System.IO
Imports System.IO.Path
Imports System.Drawing.Imaging
Imports ImageData '(The Custom Structure below)'
'*Also has a project level reference to the dso.dll referenced below.'
Public Structure ImageData
Shared FileAuthorAuthor As String
Shared FileAuthorCategory As String
Shared FileAuthorComments As String
Shared FileAuthorCompany As String
Shared FileAuthorDateCreated As DateTime
Shared FileAuthorDescription As String
Shared FileAuthorHeight As Decimal
Shared FileAuthorHeightResolution As Decimal
Shared FileAuthorImage As Image
Shared FileAuthorKeywords As String
Shared FileAuthorName As String
Shared FileAuthorPath As String 'URL or IRL'
Shared FileAuthorRead As Boolean
Shared FileAuthorSubject As String
Shared FileAuthorTitle As String
Shared FileAuthorType As String
Shared FileAuthorWidth As Decimal
Shared FileAuthorWidthResolution As Decimal
End Structure 'ImageData
And the current method for finding the data is:
Shared Function ReadExistingData(ByRef FileWithPath As String) As Boolean
'Extract the FileName'
Dim PathParts As String() = FileWithPath.Split("\") '"
Dim FileName As String = PathParts(PathParts.Length - 1)
Dim FileParts As String() = FileName.Split(".")
Dim FileType As String = FileParts(FileParts.Length - 1)
'Create an Image object. '
Dim SelectedImage As Bitmap = New Bitmap(FileWithPath)
'Get the File Info from the Image.'
Dim ImageFileInfo As New FileInfo(FileWithPath)
Dim dso As DSOFile.OleDocumentProperties
dso = New DSOFile.OleDocumentProperties
dso.Open(FileWithPath.Trim, True, DSOFile.dsoFileOpenOptions.dsoOptionOpenReadOnlyIfNoWriteAccess)
ImageData.FileAuthor = dso.SummaryProperties.Author '* Requires dso.DLL'
ImageData.FileCategory = dso.SummaryProperties.Category '* Requires dso.DLL'
ImageData.FileComments = dso.SummaryProperties.Comments '* Requires dso.DLL'
ImageData.FileCompany = dso.SummaryProperties.Company '* Requires dso.DLL'
ImageData.FileDateCreated = ImageFileInfo.CreationTime
ImageData.FileDescription = dso.SummaryProperties.Comments '* Requires dso.DLL.'
ImageData.FileHeight = SelectedImage.Height
ImageData.FileHeightResolution = SelectedImage.VerticalResolution
ImageData.FileImage = New Bitmap(FileWithPath)
ImageData.FileKeywords = dso.SummaryProperties.Keywords '* Requires dso.DLL'
ImageData.FileName = FileName
ImageData.FilePath = FileWithPath
ImageData.FileRead = ImageFileInfo.IsReadOnly
ImageData.FileSubject = dso.SummaryProperties.Subject '* Requires dso.DLL'
ImageData.FileTitle = dso.SummaryProperties.Title '* Requires dso.DLL'
ImageData.FileType = FileType
ImageData.FileWidth = SelectedImage.Width
ImageData.FileWidthResolution = SelectedImage.HorizontalResolution
Return True
End Function 'ReadExistingData'
Just a couple of the "Top Box" search hits I've reviewed:
The dso.DLL: Very Helpful, but undesirable. Requires external DLL.
[http://]www.developerfusion.com/code/5093/retrieving-the-summary-properties-of-a-file/
Incomplete Data ~ Does not answer my questions
[http://]msdn.microsoft.com/en-us/library/xddt0dz7.aspx
Requires external DLL
[http://]www.codeproject.com/KB/GDI-plus/ImageInfo.aspx
External Software required
[http://]stackoverflow.com/questions/3313474/write-metadata-to-png-image-in-net
Old Data ~ Visual Studio 2005 and .NET 2.0
[http://]www.codeproject.com/KB/graphics/MetaDataAccess.aspx
Convert to BMP: Looks useful
[http://]www.freevbcode.com/ShowCode.Asp?ID=5799
EDIT: This isn't a dll library, you just copy the source code to your project and create a new instance of the object.
I use a class called ExifWorks, found here: http://www.codeproject.com/KB/vb/exif_reader.aspx?msg=1813077 It's usage is simple,
Dim EX As New ExifWorks(bitmap)
Dim dateStr As String = EX.DateTimeOriginal
Dim description As String = EX.Description
EX.SetPropertyString(ExifWorks.TagNames.ImageDescription, "my description")
This is the easiest way I've found so far. Let me know if you run into any problems.
Dim MyValue As String = ""
For Each item In PictureBox1.Image.PropertyIdList
MyValue = System.Text.Encoding.UTF8.GetString(PictureBox1.Image.GetPropertyItem(item).Value)
ListBox1.Items.Add(MyValue)
Next