split pdf using itextpdf vb.net code - vb.net

I Have this code to split pdf file that I am using in a web application. It works fine for 1000 pages in the sense that it returns a web page after 1000 pages are split. But I have pdf containing 6000 pages and it takes more time to split a PDF with 6000 pages than it takes to split a PDF with 1000 pages. Due to the browser time-out, I get "Web Page Not Available".
What can I do to keep the connection alive?
Public Sub splitandsave(ByVal inputpath As String, ByVal outputpath As String)
obj1.getconn()
obj1.cn.Open()
Dim file As FileInfo = New FileInfo(inputpath)
Dim name As String = file.Name.Substring(0, file.Name.LastIndexOf("."))
Using reader As PdfReader = New PdfReader(inputpath)
Dim pagenumber As Integer
For pagenumber = 1 To reader.NumberOfPages
Dim email As String
Dim da As New SqlDataAdapter("select * from commondetailmaster where email!='-' order by formno", obj1.cn)
Dim ds As New DataSet
da.Fill(ds)
email = ds.Tables(0).Rows(pagenumber)("formNo").ToString
Dim quota1 As String
quota1 = "'"
Dim filename As String = quota1 & email.ToString() & quota1 & ".pdf"
Dim document As Document = New Document()
Dim copy As PdfCopy = New PdfCopy(document, New FileStream(outputpath & "\\" & filename, FileMode.Create))
document.Open()
copy.AddPage(copy.GetImportedPage(reader, pagenumber))
document.Close()
Next
End Using
End Sub

Related

how to get information from multi websites at Simultaneous by vb.net?

In my program, I get a series of information instantly from several Internet addresses on a one-to-one basis, but this is delay time and this delay may be part of the momentary information loss . I want to get all the information from all URLs at the same time. Is it possible?
This is part of my program:
For i As Integer = 0 To 1000
Dim wreq As System.Net.HttpWebRequest =
System.Net.WebRequest.Create("http://www........." + slink(i))
wreq.AutomaticDecompression = Net.DecompressionMethods.GZip
Dim wres As System.Net.WebResponse = wreq.GetResponse
Dim s As System.IO.Stream = wres.GetResponseStream
Dim sr As New System.IO.StreamReader(s)
Dim html As String = sr.ReadToEnd
Dim sOutput As String = html
Dim file As System.IO.StreamWriter
Dim masir As String = TextBox1.Text & "tm\Archive\" + slink(i).ToString
file = My.Computer.FileSystem.OpenTextFileWriter(masir, True)
file.Write(html)
file.Close()
Next

iTextSharp creates a damaged .pdf file

I am writing a "combine" .pdf file application. The .pdf file that I generate with the code below results in a .pdf file that can not be opened by Adobe. This is the code I am executing:
Dim doc_fs = CreateObject("Scripting.FileSystemObject")
Dim document_path = "C:\pdffilesfolder\"
Dim document_folder = doc_fs.GetFolder(document_path)
Dim dateArray() As String
dateArray = lblDateToPrint.Text.Split("/") 'lblDateToPrint.Text contains "3/21/2017"
If Val(dateArray(0)) < 10 Then
dateArray(0) = "0" & dateArray(0)
End If
If Val(dateArray(1)) < 10 Then
dateArray(1) = "0" & dateArray(1)
End If
Dim outFile as string = document_path & "\confirms_" & dateArray(2) & "_" & dateArray(0) & "_" & dateArray(1) & ".pdf"
Dim document = New Document
Dim writer As PdfCopy = New PdfCopy(document, New FileStream(outFile, FileMode.Create))
document.Open()
Dim fileOnServer As String = ""
Dim fileOnServerDate As String = ""
For Each item In document_folder.Files
fileOnServer = item.path
Dim reader As PdfReader = New PdfReader(fileOnServer)
writer.AddDocument(reader)
reader.Close()
Next
I have attached the 2 .pdf files that I am using as input as well as the resulting .pdf file (even through Adobe says it can not be opened).
Any assistance is greatly appreciated.
Thank you,
Jonathan
You forgot to eventually close the Document document:
Dim document = New Document
Dim writer As PdfCopy = New PdfCopy(document, New FileStream(outFile, FileMode.Create))
document.Open()
Dim fileOnServer As String = ""
Dim fileOnServerDate As String = ""
For Each item In document_folder.Files
fileOnServer = item.path
Dim reader As PdfReader = New PdfReader(fileOnServer)
writer.AddDocument(reader)
reader.Close()
Next
document.Close() ' Don't forget to close the document!

add password in a pdf file using vb.net

i just want to ask how can i add a password on a existing PDF file, i just created a pdf file using crystal reports and i kinda need to add some security features for the report. Thank you very much in advance.
lets say the file "c:\Folder1\sample.pdf" already exist. i have seen codes like the one below, but i don't know if it works because i don't know what to add in my reference to make it work
' Define input and output files path.
Dim intputFilePath As String = Program.RootPath + "\\" + "1.pdf"
Dim outputFilePath As String = Program.RootPath + "\\" + "1_with_pw.pdf"
' Set passwords for user and owner.
Dim userPassword As String = "you"
Dim ownerPassword As String = "me"
' Create password setting.
Dim setting As PasswordSetting = New PasswordSetting(userPassword, ownerPassword)
' Add password to plain PDF file and output a new file.
Dim errorCode As Integer = PDFDocument.AddPassword(intputFilePath, outputFilePath, setting)
If errorCode = 0 Then
Console.WriteLine("Success")
Else
Console.WriteLine("Failed")
End If
Dim WorkingFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim InputFile As String = Path.Combine(WorkingFolder, "PSNOs.pdf")
Dim OutputFile As String = Path.Combine(WorkingFolder, "PSNOs_enc.pdf")
Using input As Stream = New FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read)
Using output As Stream = New FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None)
Dim reader As New PdfReader(input)
PdfEncryptor.Encrypt(reader, output, True, Nothing, "secret", PdfWriter.ALLOW_SCREENREADERS)
End Using
End Using
the word "PdfReader" have an error message but it doesn't ask to import something..

Add Image And Text To Existing .pdf Using iText in VB.net

I've got the below code on a button click which work great. It adds an image to each existing .pdf and then combines several of the new .pdf's together and creates one .pdf. Again, this part of it works great.
The problem I'm having is now I want to keep the existing code but add some text to each page at the same point in the code where the image gets added. I've read a bunch of examples on how to add text to an existing .pdf but due to my inexperience in the area I cant figure out how to make any of the examples work with my existing code. Using VB.net.
I want to add a simple line of text "Example Of text" and position it on the page (300, 300).
Any help would greatly appreciated.
Dim tempFilename = IO.Path.GetTempFileName()
Dim tempFile As New IO.FileStream(tempFilename, IO.FileMode.Create)
' Set up iTextSharp document to hold merged PDF
Dim mergedDocument As New iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER)
Dim copier As New iTextSharp.text.pdf.PdfCopy(mergedDocument, tempFile)
mergedDocument.Open()
Dim pic1 As String = "C:\xxx\xxxx\xxx.png"
Using inputPdfStream As IO.Stream = New IO.FileStream(Server.MapPath(".") + "/xxx.pdf", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Using inputImageStream As IO.Stream = New IO.FileStream(pic1, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Using outputPdfStream As IO.Stream = New IO.FileStream(Server.MapPath(".") + "/xxx2.pdf", IO.FileMode.Create, IO.FileAccess.ReadWrite, IO.FileShare.None)
Dim reader1 = New iTextSharp.text.pdf.PdfReader(inputPdfStream)
Dim stamper = New iTextSharp.text.pdf.PdfStamper(reader1, outputPdfStream)
Dim pdfContentByte = stamper.GetOverContent(1)
Dim image__1 As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(inputImageStream)
image__1.SetAbsolutePosition(527, 710)
image__1.ScaleAbsolute(60, 60)
pdfContentByte.AddImage(image__1)
stamper.Close()
reader1.Close()
outputPdfStream.Close()
inputImageStream.Close()
inputPdfStream.Close()
outputPdfStream.Dispose()
End Using
End Using
End Using
Dim reader As New iTextSharp.text.pdf.PdfReader(New iTextSharp.text.pdf.RandomAccessFileOrArray(Server.MapPath(".") + "/yyy/xxx3".pdf", True), Nothing)
For pageNum = 1 To reader.NumberOfPages
copier.AddPage(copier.GetImportedPage(reader, pageNum))
Next
PTime = PTime + 1
Loop
mergedDocument.Close()
tempFile.Dispose()
After a lot of trial and error I got it to work by adding the following code.
Dim bf As iTextSharp.text.pdf.BaseFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED)
pdfContentByte.SetColorFill(iTextSharp.text.BaseColor.DARK_GRAY)
pdfContentByte.SetFontAndSize(bf, 8)
pdfContentByte.BeginText()
Dim strX As String = "Here"
pdfContentByte.ShowTextAligned(1, strX, 500, 500, 0)
pdfContentByte.EndText()

streamwriter in windows store app - write text to file in VB

Does anybody have VB code to emulate Streamwriter for Windows Store?
I know it's been replaced by StorageFolder class but there is no VB sample in MSDN and I can't seem to translate properly from c# examples. Any help would be appreciated. I am just trying to write text (CSV) to a file and save it to the documents folder. In the code below windows store want a stream instead of strPath when I try dim-ing a streamwriter. (been playing with pickerdialog too, but that might be the next hurdle).
Dim strpath As String = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary & "\" & strFileName
'Build String for file*******************
Dim swExport As StreamWriter = New StreamWriter(strpath)
swExport.Flush()
For x = 0 To intCount - 1
strLine = "WriteSomeText"
swExport.WriteLine(strLine)
Next x
Possibly the simplest approach would be to use a MemoryStream if you like StreamWriter, so something like:
Dim sessionData As New MemoryStream()
' TODO: stage data in sessionData
Dim swExport As StreamWriter = New StreamWriter(sessionData)
swExport.Flush()
For x = 0 To intCount - 1
strLine = "WriteSomeText"
swExport.WriteLine(strLine)
Next x
Dim file As StorageFile = await ApplicationData.Current.RoamingFolder.CreateFileAsync("towns.json", CreationCollisionOption.ReplaceExisting)
Using (fileStream As Stream = await file.OpenStreamForWriteAsync())
sessionData.Seek(0, SeekOrigin.Begin)
await sessionData.CopyToAsync(fileStream)
await fileStream.FlushAsync()
End Using
I was making it too difficult. To write to a file I just needed to use storagefolder and storagefile. I have also included the FileSavePicker in the code (note that filetypechoices is mandatory)
Private Async Function btnExport_Click(sender As Object, e As RoutedEventArgs) As Task
'Calls Filepicker to determine location
'Calls Sqlite to select ALL
'Creates CSV file to be saved at location chosen
'save to file
Dim intCount As Integer = "5"
Dim x As Integer
Dim strLine As String 'hold each line for export file
'Create FileName based on date
Dim strDate As String = Date.Today.ToString("MMddyyyy")
Dim strFileName As String = "Export" & strDate & ".csv"
' Configure save file dialog box
Dim dlgPicker As New Windows.Storage.Pickers.FileSavePicker
'add types for picker (manditory field)
Dim types = New List(Of String)
types.Add(".csv")
types.Add(".txt")
'set picker parameters
dlgPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads
dlgPicker.SuggestedFileName = strFileName '"Document" '
dlgPicker.FileTypeChoices.Add("CSV/TXT", types) 'manditory
dlgPicker.DefaultFileExtension = ".csv" 'Filter files by extension
dlgPicker.CommitButtonText = "Save"
' Show save file dialog box
Dim SaveCSV = Await dlgPicker.PickSaveFileAsync()
'************************get data************
Dim sbExport As Text.StringBuilder = New Text.StringBuilder
sbExport.AppendLine(strHeader)
For x = 0 To intCount - 1
strLine = "Get the text you want to write here"
sbExport.AppendLine(strLine)
Next x
'************************************
'write data to file
Await FileIO.WriteTextAsync(SaveCSV, sbExport.ToString)
Dim mb As MessageDialog = New MessageDialog("Done")
Await mb.ShowAsync()
End Function