Convert BMP file to PDF - vb.net

I want to convert a file format BMP to PDF in Visual Studio using Visual Basic technology and I use the PDFsharp library to do this.
I recieved the following error:
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in PdfSharp-wpf.dll
Additional information: The file 'E:...\bin\Debug-1493104802' does not exist.
I copied the whole contents of form to .bmp and it runs correctly. You can see my code:
Call SendMessage(TableLayoutPanel2.Handle, WM_PRINT, hdc, _ EDrawingOptions.PRF_CHILDREN Or _ EDrawingOptions.PRF_CLIENT Or _ EDrawingOptions.PRF_NONCLIENT Or _ EDrawingOptions.PRF_OWNED)
myGraphics.ReleaseHdc(hdc)
Dim doc As New PdfDocument()
doc.Pages.Add(New PdfPage())
Dim xgr As XGraphics = XGraphics.FromPdfPage(doc.Pages(0))
Dim img As XImage = XImage.FromFile(myGraphics.GetHdc)
xgr.DrawImage(img, 0, 0)
doc.Save("E:\out.pdf")
doc.Close()
' myBmp.Save("E:\out.bmp")
myGraphics.Dispose()
myGraphics = Nothing
myBmp = Nothing

After looking at your code it looks like you are generating an image using myGraphics, if that is the case you may want to save this to a tempfile, load it into the pdf and then you can delete it after you save the pdf.
Use the information on the following link to save the file.
https://stackoverflow.com/a/2881188/7436406

From your code snippet:
Dim img As XImage = XImage.FromFile(myGraphics.GetHdc)
You need a file name, but you pass an HDC? Great.
Maybe the compiler implicitly calls ToString() to make this compile. But there is no file.
Save the image to a Stream and then call XImage.FromStream to get that image in PDFsharp.

Related

How to save data to text file and retrieve

I'm using VB.NET. I am able to load the pics from a folder into a flowlayoutpanel. And then load the clicked picture into a separate picturebox and display the picture's filepath in a label.
Now I want to be able to add rating and description to each of the image in the flowlayoutpanel and save it to a text file in the folder from which the pictures have been loaded. The app should load be able to load the rating and description on the next launch or when the selected image is changed. How do I accomplish this?
You should probably look at accessing the metadata of the pic. This way the info you want is carried with the pic. This is contained in the PropertyItems Class, which is a property of the Image class
Here's a link to an answered question about adding a comment to a jpg. Hope this helps.
Here's an untested conversion of that code in VB.net. You'll probably have to add a reference or 2 and import a couple of namespaces, but syntactically this is correct as near as I can tell.
Public Function SetImageComment(input As Image, comment As String) As Image
Using memStream As New IO.MemoryStream()
input.Save(memStream, Imaging.ImageFormat.Jpeg)
memStream.Position = 0
Dim decoder As New JpegBitmapDecoder(memStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad)
Dim metadata As BitmapMetadata
If decoder.Metadata Is Nothing Then
metadata = New BitmapMetadata("jpg")
Else
metadata = decoder.Metadata
End If
metadata.Comment = comment
Dim bitmapFrame = decoder.Frames(0)
Dim encoder As BitmapEncoder = New JpegBitmapEncoder()
encoder.Frames.Add(bitmapFrame.Create(bitmapFrame, bitmapFrame.Thumbnail, metadata, bitmapFrame.ColorContexts))
Dim imageStream As New IO.MemoryStream
encoder.Save(imageStream)
imageStream.Position = 0
input.Dispose()
input = Nothing
Return Image.FromStream(imageStream)
End Using
End Function

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.

Using Spire.PDF to merge pdf files Errors

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

Why does my code throw a generic error in GDI+?

I'm trying to convert a batch of .pngs to .jpgs, as in this question:
For Each file As String In Directory.EnumerateFiles(path).Where(Function(s) s.EndsWith(".png"))
Dim newfile As String = IO.Path.Combine(newpath, IO.Path.GetFileNameWithoutExtension(file) & ".jpg")
Using png As Bitmap = Bitmap.FromFile(file)
Using jpg As New Bitmap(png.Width, png.Height)
Using g As Graphics = Graphics.FromImage(jpg)
g.Clear(Color.FromArgb(255, 212, 208, 200))
g.DrawImageUnscaled(png, 0, 0)
jpg.Save(newfile, ImageFormat.Jpeg)
End Using
End Using
End Using
Next
The call to jpg.Save, however, with a "generic error" in GDI+. Originally outside of the innermost Using statement, I moved the call inwards as per this answer, but it didn't change anything. I have verified that newfile contains a valid path, and that the program has write access to the directory. What am I missing?
I know you are saying that you are sure about the file path, but here I can see that newfile you are passing to the IO.Path.Combine have a null value.
I just initialize the newfile string with the Path string, and run your code successfully without any problem:
Dim newfile As String = Path
newfile = IO.Path.Combine(newpath, IO.Path.GetFileNameWithoutExtension(file) & ".jpg")
I've tried your code (rewritten in C#) and discovered one thing: the exception occurs only if you try to save the new image inside the same directory from which you are listing the PNGs. If you change the code to write images to a different directory, the code works without problems.
I cannot really give you an explanation of why this is happening (other than perhaps Bitmap.FromFile() is locking up the directory somehow). There are a lot of GDI+ Bitmap quirks.
BTW: I managed to rework my C# code so it doesn't throw exceptions, I'll rewrite your VB snippet in an analogous way (I haven't tested the VB code though):
For Each file As String In Directory.EnumerateFiles(path).Where(Function(s) s.EndsWith(".png"))
Dim newfile As String = IO.Path.Combine(newpath, IO.Path.GetFileNameWithoutExtension(file) & ".jpg")
Using jpg As New Bitmap(png.Width, png.Height)
Using g As Graphics = Graphics.FromImage(jpg)
Using png As Bitmap = Bitmap.FromFile(file)
g.Clear(Color.FromArgb(255, 212, 208, 200))
g.DrawImageUnscaled(png, 0, 0)
End Using
jpg.Save(newfile, ImageFormat.Jpeg)
End Using
End Using
Next
Hope it works.

How to write string data to tiff file in vb.net

I need to write some data which is string to tiff file. I am doing in the following way
Dim OFile As System.IO.File
Dim OWrite As system.IO.TextWriter
OWrite = OFile.CreateText("Signature.tiff")
OWrite.Write(ControlData)
MessageBox.Show("Signature is recieved and it is saved in Signature.tiff")
ControlData is the string which is to be written to the file.
I am capturing the signature from the user. This function gets the data in string format and i need to create a tiff file using the string data.
When i did in this way, signature.tiff is created but when i opened the image it is giving no preview available.
Can you tell me what is the problem or correct way of doing this?
Thanks a lot.
Dim format As StringFormat = New StringFormat()
Dim MyRect As Rectangle = New Rectangle(0, 0, 400, 400)
Dim MyGraphics As Graphics = Me.CreateGraphics()
Dim MyImg As Image = New Bitmap(MyRect.Width, MyRect.Height, MyGraphics)
Dim imageGraphics As Graphics = Graphics.FromImage(MyImg)
imageGraphics.FillRectangle(Brushes.White, MyRect)
format.Alignment = StringAlignment.Center
format.LineAlignment = StringAlignment.Center
imageGraphics.DrawString("Hello Everyone", objFont, Brushes.Black, RectangleF.op_Implicit(MyRect))
MyGraphics.DrawImage(MyImg, MyRect)
MyImg.Save(filename)
Just see this may help you all for converting text string to image.
Thanks.
TIFF files are binary image files. You are writing the string to a text file. Try opening the file in Notepad to check.
You need a way to create an image in memory and save it to TIFF format.
You could use a PictureBox control. Write the string onto the PictureBox then save as a TIFF.