Add Image And Text To Existing .pdf Using iText in VB.net - 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()

Related

How to replicate an image based on an integer value on ItextSharp

I am trying to make copies of a Logo according to how many times the user has inputted. But I can only make one copy of the image cause I don't know how to replicate it based on an integer value.
Here is my code:
Public Function print_logo()
Dim image as image // I cut off the file path cause I don't need that as an explanation
img.ScalePercent(40.0F) // COMPANY LOGO
img.Alignment = iTextSharp.text.Image.ALIGN_CENTER
'Exporting to PDF
Dim folderPath As String = "C:\Temp\"
If Not Directory.Exists(folderPath) Then
Directory.CreateDirectory(folderPath)
End If
Using stream As New FileStream(folderPath & "temp2.pdf", FileMode.Create)
Dim pgsize As New iTextSharp.text.Rectangle(216, 504)
Dim pdfdoc As New Document(pgsize, 15.0F, 15.0F, 10.0F, 20.0F)
PdfWriter.GetInstance(pdfDoc, stream)
pdfDoc.Open()
pdfDoc.Add(img)
pdfDoc.Close()
stream.Close()
System.Diagnostics.Process.Start("C:\\Temp\\temp2.pdf")
End Using
Return True
End Function

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..

Saving image over open file, A Generic error occurred in GDI+

I'm having trouble with my code, I'm trying to make a simple captcha for my program. The first time I run the sub it works fine, I'm guessing because the file is not "open" in my program. The second time I get the GDI+ error. I'm pretty sure this is an issue with the bitmaps being locked the 2nd time around, I'm just a little stuck.
Sub generatePasswordImage(password As String)
'This is the image where we are going to write the text on it.
Dim stringMasterImageName As String = Application.StartupPath + "\MasterImage.jpg"
Dim bitmapImage As Bitmap = New System.Drawing.Bitmap(stringMasterImageName)
Dim bitmapMasterImage As Bitmap = New System.Drawing.Bitmap(bitmapImage, New Size(400, 150))
Dim graphicsMasterImage As Graphics = Graphics.FromImage(bitmapMasterImage)
'Set the alignment based on the coordinates
Dim stringformatWriteTextFormat As StringFormat = New StringFormat()
stringformatWriteTextFormat.Alignment = StringAlignment.Center
'Do some rotation effects
Dim Generator As System.Random = New System.Random()
Dim rotation As Integer = Generator.Next(-10, 5)
graphicsMasterImage.RotateTransform(rotation)
Dim centerImgWidth As Integer = Generator.Next(CInt(graphicsMasterImage.VisibleClipBounds.Size.Width / 3), CInt(graphicsMasterImage.VisibleClipBounds.Size.Width / 2))
Dim centerImgHiehgt As Integer = Generator.Next(CInt(graphicsMasterImage.VisibleClipBounds.Size.Height / 3), CInt(graphicsMasterImage.VisibleClipBounds.Size.Height / 2))
'Set the font color
Dim colorStringColor As Color = System.Drawing.Color.Black
graphicsMasterImage.DrawString(password, New Font("Tahoma", 14, FontStyle.Bold), _
New SolidBrush(colorStringColor), New Point(centerImgWidth, centerImgHiehgt), stringformatWriteTextFormat)
Dim stringOutPutFileName As String = Application.StartupPath + "\Pass.jpg"
bitmapMasterImage.Save(stringOutPutFileName, System.Drawing.Imaging.ImageFormat.Jpeg)
bitmapMasterImage.Dispose()
bitmapImage.Dispose()
End Sub

split pdf using itextpdf vb.net code

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

How do I reload the formatted text into RTB?

I have a RTB in VB.NET, and put an event handler to save the formatted text into a file after encrypting it. However, I can't figure out how to reload the formatting - when I open it, it shows the symbols of formatting instead of formatted text. Here's my code:
Dim FileName As String = TextBox1.Text
File.Delete(FileName)
Dim EncryptElement As New TripleDESCryptoServiceProvider
EncryptElement.Key = {AscW("B"c), AscW("A"c), AscW("1"c), AscW("R"c), AscW("3"c), AscW("9"c), AscW("G"c), AscW("V"c), AscW("5"c), AscW("S"c), AscW("P"c), AscW("0"c), AscW("L"c), AscW("Z"c), AscW("4"c), AscW("M"c)} '128 bit Key
EncryptElement.IV = {AscW("N"c), AscW("B"c), AscW("5"c), AscW("3"c), AscW("G"c), AscW("L"c), AscW("2"c), AscW("Q"c)} ' 64 bit Initialization Vector
Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)
Dim cStream As New CryptoStream(fStream, New TripleDESCryptoServiceProvider().CreateEncryptor(EncryptElement.Key, EncryptElement.IV), CryptoStreamMode.Write)
Dim sWriter As New StreamWriter(cStream)
sWriter.WriteLine(RichTextBox1.Rtf)
sWriter.Close()
cStream.Close()
fStream.Close()
The above code is for saving, and the below code is for opening.
Dim FileName As String = TextBox1.Text
Dim DecryptElement As New TripleDESCryptoServiceProvider
DecryptElement.Key = {AscW("B"c), AscW("A"c), AscW("1"c), AscW("R"c), AscW("3"c), AscW("9"c), AscW("G"c), AscW("V"c), AscW("5"c), AscW("S"c), AscW("P"c), AscW("0"c), AscW("L"c), AscW("Z"c), AscW("4"c), AscW("M"c)}
DecryptElement.IV = {AscW("N"c), AscW("B"c), AscW("5"c), AscW("3"c), AscW("G"c), AscW("L"c), AscW("2"c), AscW("Q"c)}
Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)
Dim cStream As New CryptoStream(fStream, New TripleDESCryptoServiceProvider().CreateDecryptor(DecryptElement.Key, DecryptElement.IV), CryptoStreamMode.Read)
Dim sReader As New StreamReader(cStream)
Dim DecryptedData As String = ""
DecryptedData = sReader.ReadToEnd
RichTextBox1.AppendText(DecryptedData)
RichTextBox1.Enabled = True
Button1.Text = "OK"
sReader.Close()
cStream.Close()
fStream.Close()
Where is the problem?
You need RichTextBox1.SaveFile(SomeStream, RichTextBoxStreamType) I think StreamWriter is stuffing it up.
Oh and seeing as you just gave the world the keys for your encryption you might want to come up with a new one...
Added after comment not proven though.
Replace these two lines in your save routine
Dim sWriter As New StreamWriter(cStream)
sWriter.WriteLine(RichTextBox1.Rtf)
with
RichTextBox1.SaveFile(cStream,RichTextBoxStreamType.RichText);
and get rid of swriter.Close()
I think.