Converting multiple Images to pdf using pdfsharp - vb.net

I am trying to convert multiple images to pdf using pdfsharp library.
I am able to convert single image and it works pretty well.
And while converting bulk images to single pdf I am facing problem that it takes all the images and converts them but after conversion If I check it shows me only the last image as it is not appending to the existing image and it overwrites the previous image.
So how do I rectify this?
Any help will be appreciated as I am first time working with pdf library and point me out If I am doing any mistake.And I will be gald to know more about this and I don't feel though If you pointed me out the mistake I have done.
Here is my code:
Private Sub btnAddFolder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddFolder.Click
If Me.FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim f As New DirectoryInfo(Me.FolderBrowserDialog1.SelectedPath)
Dim fso As New System.Object
For Each file As FileInfo In f.GetFiles
Select Case file.Extension.ToLower
Case ".jpg", ".bmp", ".gif", ".png"
Me.ThumbControl1.BackgroundImage = Nothing
Me.CheckedListBox1.Items.Add(file.FullName, CheckState.Checked)
Me.ThumbControl1.AddThumbnail(file.FullName)
Me.ThumbControl1.BackgroundImage = Nothing
Me.CheckedListBox1.SelectedIndex = 0
End Select
Next
End If
End Sub
Background worker:
Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bw.DoWork
For pix As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
Try
Dim source As String = CheckedListBox1.Items(pix).ToString()
Dim destinaton As String = (TryCast(e.Argument, String()))(1)
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(source)
xgr.DrawImage(img, 0, 0)
doc.Save(destinaton)
doc.Close()
success = True
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Next
End Sub
Convert button:
Private Sub btnConvert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConvert.Click
bw.RunWorkerAsync(New String(1) {srcFile, destFile})
End sub
Saving Pdf:
Private Sub btnSelectDest_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSelectDest.Click
sfdDestFile.Filter = "PDF Files(*.pdf)|*.pdf"
If sfdDestFile.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then
Return
End If
destFile = sfdDestFile.FileName
End Sub

The problem is that you are creating a new PDF document on each pass through the loop. You need to move this outside the loop. Also, you are referencing page 0, not page pix. Here is how I would fix it:
Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bw.DoWork
Dim doc As New PdfDocument()
For pix As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
Try
Dim source As String = CheckedListBox1.Items(pix).ToString()
Dim oPage As New PDFPage()
doc.Pages.Add(oPage)
Dim xgr As XGraphics = XGraphics.FromPdfPage(oPage)
Dim img As XImage = XImage.FromFile(source)
xgr.DrawImage(img, 0, 0)
success = True
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Next
Dim destinaton As String = (TryCast(e.Argument, String()))(1)
doc.Save(destinaton)
doc.Close()
End Sub

Related

Reading and writing files causes "The process cannot access the file because it is being used by another process" error

I'm very new to coding so my code is very basic but I am trying to rewrite a file using an item selected from a list box. The code is a recreation of my full code so it's not as thorough but I want to be able to change the "availability" of a product for a website (In theory because this is not a professional project). When I try to read or write the file an error message comes up saying "The process cannot access the file because it is being used by another process".
Dim FileRewrite As String = "FileRewrite.txt"
Dim ValidateID As Boolean
Dim Read As String
Dim IDR As String
Dim YNR As String
Private Sub TxtBxID_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtBxID.TextChanged
If TxtBxID.Text.Length = 2 Then
ValidateID = True
Else
ValidateID = False
End If
End Sub
Private Sub BtnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAdd.Click
Dim ID As String
Dim YN As String
Dim Writer As New System.IO.StreamWriter(FileRewrite, True)
If ValidateID = True Then
ID = TxtBxID.Text
If CBxYN.Checked = True Then
YN = "YES"
Else
YN = "NO "
End If
Writer.WriteLine(LSet(ID, 3) & LSet(YN, 3))
Writer.Close()
LstBxItems.Items.Clear()
Dim Reader As New System.IO.StreamReader(FileRewrite, True)
Do While Reader.Peek >= 0
LstBxItems.Items.Add(Reader.ReadLine)
Loop
Reader.Close()
Else
MsgBox("Please enter a 2 digit ID")
End If
End Sub
Private Sub BtnChange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnChange.Click
Dim ItemToChange As String
Dim Reader As New System.IO.StreamReader(FileRewrite, True)
ItemToChange = LstBxItems.SelectedItem
IDR = Mid(ItemToChange, 1, 3)
YNR = Mid(ItemToChange, 4, 6)
Do While Reader.Peek >= 0
Read = Reader.ReadLine
Writer()
Loop
Reader.Close()
End Sub
Private Sub Writer()
Dim Writer As New System.IO.StreamWriter(FileRewrite, True)
If Mid(Read, 1, 3) = IDR Then
If YNR = "YES" Then
YNR = "NO "
Else
YNR = "YES"
End If
Writer.WriteLine(LSet(IDR, 3) & LSet(YNR, 3))
Writer.Close()
End If
End Sub
I expect the availability of the product in the file to change from yes to no or no to yes but the reader and writer will not work
You cannot write to the file while looping through the same file to read via Reader.Peek

Download a file from google drive

First of all, sorry for my english. Second, I want to make an app that, at every launch download a .txt file from google drive, the file is defined (I mean, it's in drive). It's just a single file, but, when I launch the app, the file is downloaded, but dosen't contain anything..
Here is my code:
Private Function ReadLine(ByVal Line As Integer, ByVal lista As List(Of String)) As String
Return lista(Line - 1)
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If My.Computer.Network.IsAvailable() = True Then
Try
My.Computer.FileSystem.DeleteFile("C:\WINDOWS\" & fisier)
Catch ex As Exception
End Try
My.Computer.Network.DownloadFile("https://doc-14-7c-docs.googleusercontent.com/docs/securesc/17t22h2a63tpkhdgv047v6i0s5a9o8bm/qgqjocmi87jt0up72gfpg9dseeo3pt84/1458396000000/07699472972018131827/07699472972018131827/0B8iVIf__yN1FUDV1STNWODJUYms?e=download&nonce=5jnki0mtgo520&user=07699472972018131827&hash=0gi5r6k7rm2uob14062tlbsk0nhpkoo1", _
"C:\WINDOWS\" & fisier)
Dim reader As New IO.StreamReader("C:\WINDOWS\" & fisier)
Dim lista As New List(Of String)
While Not reader.EndOfStream
lista.Add(reader.ReadLine)
End While
reader.Close()
If My.Computer.FileSystem.FileExists(fisier2) = False Then
lblWould.Text = ReadLine(1, lista)
Else
Dim nr As Integer
nr = Val(My.Computer.FileSystem.ReadAllText(fisier2))
nrx = nr
End If
Dim contain As String = My.Computer.FileSystem.ReadAllText("C:\WINDOWS\" & fisier)
contain = contain.Replace(lblWould.Text, "SEEN!")
My.Computer.FileSystem.WriteAllText("C:\WINDOWS\" & fisier, contain, False)
Else
MsgBox("Trebuie sa fi connectat la internet!")
Me.Close()
End If
End Sub
Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnYes.Click, btnNo.Click
Dim reader As New IO.StreamReader("C:\WINDOWS\" & fisier)
Dim lista As New List(Of String)
Dim a As String
While Not reader.EndOfStream
a = reader.ReadLine()
If Not a = "SEEN!" Then
lista.Add(reader.ReadLine)
End If
End While
lblWould.Text = lista(nrx + 1)
nrx += 1
Dim contain As String = My.Computer.FileSystem.ReadAllText("C:\WINDOWS\" & fisier)
contain = contain.Replace(lblWould.Text, "SEEN!")
My.Computer.FileSystem.WriteAllText("C:\WINDOWS\" & fisier, contain, False)
End Sub`
Thanks!

How do I get a value from a dynamic control?

I've got a form with a picturecontrol (default to black bg) and I have a flowlayoutpanel underneath. On the form's load it cycles through a folder of images and creates a thumbnail (picturecontrol) inside the flowlayoutpanel. What I want to do is dynamically add a click event to let the user change the main picturecontrol image with one of the thumbnails.
Private Sub TabImageLoad()
Dim apppath As String = Application.StartupPath()
Dim strFileSize As String = ""
Dim di As New IO.DirectoryInfo(apppath + "\images")
Dim aryFi As IO.FileInfo() = di.GetFiles("*.*")
Dim fi As IO.FileInfo
For Each fi In aryFi
If fi.Extension = ".jpg" Or fi.Extension = ".jpeg" Or fi.Extension = ".gif" Or fi.Extension = ".bmp" Then
Dim temp As New PictureBox
temp.Image = Image.FromFile(di.ToString + "\" + fi.ToString)
temp.Width = 100
temp.Height = 75
temp.Name = fi.ToString
temp.Visible = True
temp.SizeMode = PictureBoxSizeMode.StretchImage
AddHandler temp.Click, AddressOf Me.temp_click
FlowLayoutPanel1.Controls.Add(temp)
End If
Next
End Sub
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
PictureBox1.Image = temp.Image
End Sub
This is my code for the sub that gets the images (note the addhandler attempt) and the sub that links to the addhandler. As you've probably guessed the addhandler doesn't work because "temp" is not declared in the temp_click sub.
Any suggestions?
The sender argument is always the control that triggered the event, in this case a PictureBox:
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim pb As PictureBox = DirectCast(sender, PictureBox)
PictureBox1.Image = pb.Image
End Sub
I suggest you to use:
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim pbDynamic as PictureBox = trycast(sender,Picturebox)
Then validate with
if pbDynamic IsNot Nothing Then
PictureBox1.Image = pbDynamic.image
end if
This way you avoid runtime errors and null pointer exceptions

Drawing a WebBrowser control to a bitmap

I'm trying to save a panel control as a bitmap using the following code (VB.net):
Private Sub SaveFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles SaveFileDialog1.FileOk
filename = SaveFileDialog1.FileName
Dim CardImg As New Bitmap(Panel1.Width, Panel1.Height)
Panel1.DrawToBitmap(CardImg, Panel1.ClientRectangle)
CardImg.Save(filename, System.Drawing.Imaging.ImageFormat.Bmp)
End Sub
Everything works, except the Web browser control, which is docked in the panel. In the saved bitmap, this control appears as only white space, while everything else in the panel renders out fine. Any ideas?
When I saved snapshots from a WebBrowser I called .Focus() on it after navigating -- and somehow the white picture results magically disapperard. Don't know why, but it worked for me.
Download "ScreenCapture.vb" from http://www.vbforums.com/showthread.php?t=385497,
use CaptureDeskTopRectangle but you should not use the location of your panel because it's
referenced to panel parent you should use yourpanel.PointToScreen() to identify the correct
rectangle.
Regards..
UPDATE:
Check this out, you gon like it, i similute your case and it's working:
Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
Try
Using fl As New SaveFileDialog
fl.Filter = "PNG images|*.png"
If fl.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim sc As New screencapture
Dim pt = WebBrowser1.Parent.PointToScreen(WebBrowser1.Location)
Dim rec As New Rectangle(pt.X, pt.Y, WebBrowser1.Width, WebBrowser1.Height)
Application.DoEvents()
Threading.Thread.Sleep(500)
Using bmp As Bitmap = sc.CaptureDeskTopRectangle(rec, WebBrowser1.Width, WebBrowser1.Height)
bmp.Save(fl.FileName, System.Drawing.Imaging.ImageFormat.Png)
End Using
End If
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Update 2:
In Form:
Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
Try
Using fl As New SaveFileDialog
fl.Filter = "PNG images|*.png"
If fl.ShowDialog = Windows.Forms.DialogResult.OK Then
JSsetTimeout.SetTimeout(Me, "TakeShot", 1500, fl.FileName)
End If
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Sub TakeShot(ByVal FilePath As String)
Try
Application.DoEvents()
Dim sc As New screencapture
Dim pt = WebBrowser1.Parent.PointToScreen(WebBrowser1.Location)
Dim rec As New Rectangle(pt.X, pt.Y, WebBrowser1.Width, WebBrowser1.Height)
Using bmp As Bitmap = sc.CaptureDeskTopRectangle(rec, WebBrowser1.Width, WebBrowser1.Height)
bmp.Save(FilePath, System.Drawing.Imaging.ImageFormat.Png)
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
To Create a time delay add the class below :
Public Class JSsetTimeout
Public res As Object = Nothing
Dim WithEvents tm As Timer = Nothing
Dim _MethodName As String
Dim _args() As Object
Dim _ClassInstacne As Object = Nothing
Public Shared Sub SetTimeout(ByVal ClassInstacne As Object, ByVal obj As String, ByVal TimeSpan As Integer, ByVal ParamArray args() As Object)
Dim jssto As New JSsetTimeout(ClassInstacne, obj, TimeSpan, args)
End Sub
Public Sub New(ByVal ClassInstacne As Object, ByVal obj As String, ByVal TimeSpan As Integer, ByVal ParamArray args() As Object)
If obj IsNot Nothing Then
_MethodName = obj
_args = args
_ClassInstacne = ClassInstacne
tm = New Timer With {.Interval = TimeSpan, .Enabled = False}
AddHandler tm.Tick, AddressOf tm_Tick
tm.Start()
End If
End Sub
Private Sub tm_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tm.Tick
tm.Stop()
RemoveHandler tm.Tick, AddressOf tm_Tick
If Not String.IsNullOrEmpty(_MethodName) AndAlso _ClassInstacne IsNot Nothing Then
res = CallByName(_ClassInstacne, _MethodName, CallType.Method, _args)
Else
res = Nothing
End If
End Sub
End Class

Read Text File and Output Multiple Lines to a Textbox

I'm trying to read a text file with multiple lines and then display it in a textbox. The problem is that my program only reads one line. Can someone point out the mistake to me?
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private BagelStreamReader As StreamReader
Private PhoneStreamWriter As StreamWriter
Dim ResponseDialogResult As DialogResult
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
'Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
'Is file already open
If PhoneStreamWriter IsNot Nothing Then
PhoneStreamWriter.Close()
End If
With OpenFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
'If ResponseDialogResult <> DialogResult.Cancel Then
' PhoneStreamWriter = New StreamWriter(OpenFileDialog1.FileName)
'End If
Try
BagelStreamReader = New StreamReader(OpenFileDialog1.FileName)
DisplayRecord()
Catch ex As Exception
MessageBox.Show("File not found or is invalid.", "Data Error")
End Try
End Sub
Private Sub DisplayRecord()
Do Until BagelStreamReader.Peek = -1
TextBox1.Text = BagelStreamReader.ReadLine()
Loop
'MessageBox.Show("No more records to display.", "End of File")
'End If
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
With SaveFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
PhoneStreamWriter.WriteLine(TextBox1.Text)
With TextBox1
.Clear()
.Focus()
End With
TextBox1.Clear()
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
PhoneStreamWriter.Close()
Me.Close()
End Sub
End Class
Here is a sample textfile:
Banana nut
Blueberry
Cinnamon
Egg
Plain
Poppy Seed
Pumpkin
Rye
Salt
Sesame seed
You're probably only getting the last line in the file, right? Your code sets TextBox1.Text equal to BagelSteramReader.ReadLine() every time, overwriting the previous value of TextBox1.Text. Try TextBox1.Text += BagelStreamReader.ReadLine() + '\n'
Edit: Though I must steal agree with Hans Passant's commented idea on this; If you want an more efficient algorithm, File.ReadAllLines() even saves you time and money...though I didn't know of it myself. Darn .NET, having so many features...
I wrote a program to both write to and read from a text file. To write the lines of a list box to a text file I used the following code:
Private Sub txtWriteToTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtWriteToTextfile.Click
Dim FileWriter As StreamWriter
FileWriter = New StreamWriter(FileName, False)
' 3. Write some sample data to the file.
For i = 1 To lstNamesList.Items.Count
FileWriter.Write(lstNamesList.Items(i - 1).ToString)
FileWriter.Write(Chr(32))
Next i
FileWriter.Close()
End Sub
And to read and write the contents of the text file and write to a multi-line text box (you just need to set the multiple lines property of a text box to true) I used the following code. I also had to do some extra coding to break the individual words from the long string I received from the text file.
Private Sub cmdReadFromTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReadFromTextfile.Click
Dim sStringFromFile As String = ""
Dim sTextString As String = ""
Dim iWordStartingPossition As Integer = 0
Dim iWordEndingPossition As Integer = 0
Dim iClearedTestLength As Integer = 0
Dim FileReader As StreamReader
FileReader = New StreamReader(FileName)
sStringFromFile = FileReader.ReadToEnd()
sTextString = sStringFromFile
txtTextFromFile.Text = ""
Do Until iClearedTestLength = Len(sTextString)
iWordEndingPossition = CInt(InStr((Microsoft.VisualBasic.Right(sTextString, Len(sTextString) - iWordStartingPossition)), " "))
txtTextFromFile.Text = txtTextFromFile.Text & (Microsoft.VisualBasic.Mid(sTextString, iWordStartingPossition + 1, iWordEndingPossition)) & vbCrLf
iWordStartingPossition = iWordStartingPossition + iWordEndingPossition
iClearedTestLength = iClearedTestLength + iWordEndingPossition
Loop
FileReader.Close()
End Sub