This is my code
Dim doc As iTextSharp.text.Document = New iTextSharp.text.Document()
Dim path As String = Request.MapPath("Sample PDFs") & "\Sample.tif"
PdfWriter.GetInstance(doc, New FileStream(Request.PhysicalApplicationPath + _
"render\1.pdf", FileMode.Create))
Dim data As clsData = New clsData(GetConnection, enumEgswFetchType.DataTable)
Dim int As Integer = data.GetPageCount(path)
doc.Open()
For ctr As Integer = 0 To int - 1
Dim img As iTextSharp.text.Image
Dim image As New System.Web.UI.WebControls.Image
image.ImageUrl = "ctrls/ViewTif.aspx?path=" + path.ToString + "&page=" + ctr.ToString
img = iTextSharp.text.Image.GetInstance(image, System.Web.UI.WebControls.Image)
doc.Add(image)
Next
doc.Close()
Response.Redirect("~/1.pdf")
Is there any way that I can get the webcontrol image to the itext? the image variable is a dynamic image with a source page returning a jpeg image from a tif file. Or is there any way I can directly put the tif to itext as pdf?
Is there a reason that you need to use System.Web.UI.WebControls.Image? One of the overloads for iTextSharp.text.Image.GetInstance() accepts a URL:
Dim TestFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf")
Using FS As New FileStream(TestFile, FileMode.Create, FileAccess.Write, FileShare.None)
Using Doc As New Document()
Using Writer = PdfWriter.GetInstance(Doc, FS)
Doc.Open()
Doc.Add(New Paragraph("Hello World"))
''//Get the image from a URL
Dim Img = iTextSharp.text.Image.GetInstance("http://www.google.com/images/srpr/logo4w.png")
''//Optionally adjust it
Img.ScaleAbsolute(100, 200)
''//Add it to the document
Doc.Add(Img)
Doc.Close()
End Using
End Using
End Using
Related
In the application I am working on I need to resize a picture and add it to the database I have implemented something to do so but I have a problem saving the resulting BMP file in the memory stream so that my implementation works with the existing code.Also the source from my image comes from a variable called fu (File upload object) I was also wondering if the way to access the source of the file is to use fu.name or fu.Filecontents. Also I have Enclosed what I implemented in beginning of my implementation and Ending of my implementation as the other code was done by a colleague who is not with me anymore.
Here is the code:
Public Function UploadFile(fu As FileUpload, expID As Integer) As Integer
GetConnectionString()
Dim con As New SqlConnection(connString.ConnectionString)
Dim dataAdapter As New SqlDataAdapter
Dim myCommandBuilder As SqlCommandBuilder
Dim dataSet As New DataSet
Dim memoryStream As MemoryStream
Dim bData As Byte()
Dim reader As BinaryReader
Dim expense As New Expense(expID)
Dim loggedInUser As New Employee(Membership.GetUser.UserName)
Try
UploadFile = 1
'check that the logged in user has the right to attach a file to the current expense
If loggedInUser.ID = expense.Rpt.Emp.ID Or loggedInUser.ID = expense.Rpt.Emp.Supervisor Or loggedInUser.ID = expense.Rpt.Emp.Finalizer Or loggedInUser.ID = expense.Rpt.Emp.DelegatedTo Then
If fu.HasFile Then
If fu.FileContent.Length < 5000000 Then
dataAdapter = New SqlDataAdapter("SELECT * FROM tblExpense WHERE EXPENSE_ID=" & expID, con)
myCommandBuilder = New SqlCommandBuilder(dataAdapter)
dataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
con.Open()
dataAdapter.Fill(dataSet, "tblExpense")
'Begining of my implementation
' Get the scale factor.
Dim scale_factor As Single = Single.Parse(0.33)
' Get the source bitmap.
Dim bm_source As New Bitmap(fu.FileContent)
' Make a bitmap for the result.
Dim bm_dest As New Bitmap(
CInt(bm_source.Width * scale_factor),
CInt(bm_source.Height * scale_factor))
' Make a Graphics object for the result Bitmap.
Dim gr_dest As Graphics = Graphics.FromImage(bm_dest)
' Copy the source image into the destination bitmap.
gr_dest.DrawImage(bm_source, 0, 0,
bm_dest.Width + 1,
bm_dest.Height + 1)
'Ending of my implementation
reader = New BinaryReader(fu.FileContent)
bData = reader.ReadBytes(reader.BaseStream.Length)
memoryStream = New MemoryStream(bData, 0, bData.Length)
memoryStream.Close()
dataSet.Tables("tblExpense").Rows(0)("RECEIPT") = bData
Select Case UCase(Right(fu.PostedFile.FileName, 3))
Case "JPG" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "image/jpeg"
Case "PNG" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "image/png"
Case "GIF" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "image/gif"
Case "PDF" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "application/pdf"
Case "TXT" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "text/plain"
Case "HTM" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "text/html"
Case "HTML" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "text/html"
Case Else : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "image/jpeg"
End Select
dataSet.Tables("tblExpense").Rows(0)("RECEIPT_NAME") = expense.Rpt.Emp.EmpNum & "-" & expense.Rpt.Name & "-" & expense.ID
dataSet.Tables("tblExpense").Rows(0)("RECEIPT_DATE") = Now
dataAdapter.Update(dataSet, "tblExpense")
Else
UploadFile = 2
Reading an JSON document "source.json" thru filestream but how do you get the data from the json file? After that I am trying to append the newly edited json data back on the same file.
Dim pathSource As String = "Server.MapPath('~/source.json')"
Try
Using fs As FileStream = New FileStream(pathSource, _
FileMode.Open, FileAccess.Read)
Dim bytes() As Byte = New Byte((fsSource.Length) - 1) {}
Dim numBytesToRead As Integer = CType(fsSource.Length,Integer)
Dim numBytesRead As Integer = 0
While (numBytesToRead > 0)
Dim n As Integer = fsSource.Read(bytes, numBytesRead, _
numBytesToRead)
If (n = 0) Then
Exit While
End If
numBytesRead = (numBytesRead + n)
numBytesToRead = (numBytesToRead - n)
End While
numBytesToRead = bytes.Length
Dim xmlBuilder = New StringBuilder()
fs.Seek(0, SeekOrigin.Begin)
Dim ms As New MemoryStream()
fs.CopyTo(ms)
xmlBuilder.Append(Encoding.UTF8.GetString(ms.ToArray()))
ms.Flush()
ms.Close()
'???How to access the data from the file "source.json" you just read in???
'Edit the file "source.json" data
?? How to put it into "bytesout" the edited data???
Using fsAppend As FileStream = New FileStream(pathSource, _
FileMode.Append, FileAccess.Write)
fsAppend.Write(bytesout, 0, numBytesToRead)
End Using
End Using
Catch ioEx As FileNotFoundException
Console.WriteLine(ioEx.Message)
End Try
I've been down that path. Try to figure out what you did wrong with newtonsoft. The serializer and deserializer methods are fairly easy to use. You only have to create an object per the Json format and deserializer will populate the object automatically. You just have to have the variables in the class be declared as public property nameofjsonobject as
Here is my issue: I'm trying to read JPG files from a folder and convert them to one PDF file for example if in my folder I have 1).Hello.jpg 2). World.jpg I want to grab those files and combined it to a one PDF file so the result will be
newPDF.pdf
I'm reading the images correctly from the folder adding them to the document but it's not creating the new PDF file in the folder. How can I solve this??
Here is my code:
'!=Orginally after setting all the files in the folder we need to read the path from the session file.
'!= After reading the path we need to read each file from the folder and generate one pdf file.
Dim attachmentsFolder As String = "E:/IRAttachments/PSC/2013/2/IR-7264"
Dim fileName As String = String.Concat("IR_7264(", DateTime.Now.ToString("yyyyMMddHHmmssfff").ToString(), ").pdf")
Dim finalPathName As String = String.Concat(attachmentsFolder, "/", fileName)
'!= Step 2). read the pdf/images from folder and merge them to a one pdf file.
Dim files As New List(Of String)()
Dim readerList As New List(Of PdfReader)()
m_HashTableIRAttachments = New Hashtable
m_DictionaryEntryIRAttachments = New DictionaryEntry
Dim fileExtentionType As String = String.Empty
Dim doc As Document = New Document
For Each filePath As String In Directory.GetFiles(attachmentsFolder)
fileExtentionType = filePath.Substring(filePath.LastIndexOf("."))
If fileExtentionType = ".jpg" Then '# Get the extension type
Dim document As New Document()
Using stream = New FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)
PdfWriter.GetInstance(document, stream)
document.Open()
Using imageStream = New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim image__1 = Image.GetInstance(imageStream)
document.Add(image__1)
Dim pdfFile As String = finalPathName
End Using
document.Close()
End Using
'PdfWriter.GetInstance(doc, New FileStream(Request.PhysicalApplicationPath + fileName, FileMode.Create))
'doc.Open()
'doc.Add(New Paragraph("Hello World"))
'Dim myDoc As New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
'Dim pdfFile As String = finalPathName
'Dim writer As PdfWriter = PdfWriter.GetInstance(myDoc, New FileStream(pdfFile, FileMode.Create))
'myDoc.Open()
'Dim para As New Paragraph("Let's write some text before inserting image.")
'Dim myImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(filePath)
'myImage.ScaleToFit(300.0F, 250.0F)
'myImage.SpacingBefore = 50.0F
'myImage.SpacingAfter = 10.0F
'myImage.Alignment = Element.ALIGN_CENTER
'myDoc.Add(para)
'myDoc.Add(myImage)
'myDoc.Close()
'doc.Close()
Else
'# Means it's a pdf and not a jpg file.
Dim pdfReader1 As New PdfReader(filePath)
readerList.Add(pdfReader1)
End If
Next
When you create the Stream for your PDF file, you are using the fileName variable, which is only the name, not the full path. It is likely that the PDF is being created - just not where you are expecting it to be. You probably want to use finalPathName instead:
Using stream = New FileStream(finalPathName, FileMode.Create, FileAccess.Write, FileShare.None)
I would also recommend you take a look at the methods available on the System.IO.Path class, and use them when constructing file paths and getting the file extension, e.g.
Dim finalPathName As String = Path.Combine(attachmentsFolder, fileName)
'...
fileExtentionType = Path.GetExtension(filePath)
' etc.
EDIT
It looks like you are also overwriting the PDF file for each image file, while I would imagine you want all of the images in one PDF file. Your loop for the images should probably be inside the Using stream = ... block (e.g. between document.Open() and document.Close()).
I have my temp PDF on the network and am using asp to fill in the fields and then download the file.
The problem I have is that the file downloaded is just the blank template, none of the fields are filled?
My code
Dim doc As New Document(PageSize.A4.Rotate)
Dim ms As New MemoryStream()
Dim writer = PdfWriter.GetInstance(doc, ms)
writer.Open()
Dim PdfR As New PdfReader("http://192.168.0.221/template.pdf")
Dim PdfS As New PdfStamper(PdfR, ms)
Dim fields As AcroFields = PdfS.AcroFields
fields.SetField("s1", "00")
fields.SetField("pono", "100")
PdfS.FormFlattening = True
PdfS.Close()
PdfR.Close()
Dim r = System.Web.HttpContext.Current.Response
r.ContentType = "application/pdf"
r.AddHeader("Content-Disposition", String.Format("attachment;filename=Testing.pdf", "Testing"))
r.BinaryWrite(ms.ToArray)
If anyone else ever hits this issue
1) If you dont mind your fields being editable then remove the FormFlattening command
2) Else add this fields.GenerateAppearances = True
I'm using a function that uploads an image, takes the stream and resizes it using imageresizer.net, then uploads the stream to Amazon S3.
Now I want to take a local picture and convert it into a stream. (to resize and upload to amazonS3). Basically, how do you convert an image into a stream.
This might be a simple question, just could not find the answer anywhere.
Here is some basic code.
Public Shared Sub MoveToAmazon(strImg As String, SKU As String)
Dim fullImg As String = "C:\ImageLocation\" & strImg
Dim img As Image = Image.FromFile(fullImg)
'Here Im missing the code to convert it to a stream.
UploadImage(imgStream, SKU)
End Sub
Public Shared Sub UploadImage(imgStream As Stream, imgName As String)
Dim MainStream As Stream = New MemoryStream
Dim HomeStream As Stream = New MemoryStream
Dim SmallStream As Stream = New MemoryStream
Dim TinyStream As Stream = New MemoryStream
Dim MidStream As Stream = New MemoryStream
Dim GridStream As Stream = New MemoryStream
Dim ListStream As Stream = New MemoryStream
Dim c As New ImageResizer.Configuration.Config
Dim SourceImage As Bitmap = New Bitmap(imgStream)
Dim SourceMain As Bitmap = New Bitmap(SourceImage)
Dim SourceHome As Bitmap = New Bitmap(SourceImage)
Dim SourceSmall As Bitmap = New Bitmap(SourceImage)
Dim SourceTiny As Bitmap = New Bitmap(SourceImage)
Dim SourceMid As Bitmap = New Bitmap(SourceImage)
Dim SourceGrid As Bitmap = New Bitmap(SourceImage)
Dim SourceList As Bitmap = New Bitmap(SourceImage)
ImageResizer.ImageBuilder.Current.Build(SourceMain, MainStream, New ResizeSettings("width=300&height=372&scale=both&paddingWidth=40")) 'ProductPage
ImageResizer.ImageBuilder.Current.Build(SourceHome, HomeStream, New ResizeSettings("width=112&height=147&scale=both")) 'HomePage Products
ImageResizer.ImageBuilder.Current.Build(SourceGrid, GridStream, New ResizeSettings("width=149&height=149&scale=both")) 'Categories Grid
ImageResizer.ImageBuilder.Current.Build(SourceList, ListStream, New ResizeSettings("width=171&height=206&scale=both")) 'Categories List
ImageResizer.ImageBuilder.Current.Build(SourceSmall, SmallStream, New ResizeSettings("width=64&height=75&scale=both")) 'Accessories
ImageResizer.ImageBuilder.Current.Build(SourceTiny, TinyStream, New ResizeSettings("width=82&height=82&scale=both")) 'Cart
ImageResizer.ImageBuilder.Current.Build(SourceMid, MidStream, New ResizeSettings("width=155&height=116&scale=both")) 'CategoryMain
AmazonUploadFile("OriginalImages/" & imgName, imgStream)
AmazonUploadFile("MainImages/" & imgName, MainStream)
AmazonUploadFile("HomeImages/" & imgName, HomeStream)
AmazonUploadFile("GridImages/" & imgName, GridStream)
AmazonUploadFile("ListImages/" & imgName, ListStream)
AmazonUploadFile("SmallImages/" & imgName, SmallStream)
AmazonUploadFile("TinyImages/" & imgName, TinyStream)
AmazonUploadFile("MidImages/" & imgName, MidStream)
End Sub
Public Shared Sub AmazonUploadFile(S3Key As String, FileStream As Stream)
Dim request As New PutObjectRequest()
request.WithBucketName(BUCKET_NAME)
request.WithKey(S3Key).InputStream = FileStream
request.WithCannedACL(S3CannedACL.PublicRead)
GetS3Client.PutObject(request)
End Sub
[Disclaimer - I'm the author of the ImageResizing.NET library the OP is asking the question about.]
Folks - do NOT use Bitmap and Image instances if you can possibly avoid it. There is a giant list of pitfalls that will crash your server. Do NOT use ANYTHING from System.Drawing without a server-safe wrapper around it.
#dash - Your code is almost right, aside from the memory leaks.
Decoding and encoding images safely isn't straightforward. Let the ImageResizing.Net library handle it.
Dim settings as New ResizeSettings("width=64&height=75&scale=both")
Using ms As New MemoryStream()
ImageBuilder.Current.Build("C:\ImageLocation\" & strImg, ms, settings)
ms.Seek(0, SeekOrigin.Begin)
UploadImage(ms, SKU)
End Using
Never load something into a Bitmap or Image instance if you're making multiple versions. Clone the file into a MemoryStream instead.
Using fs as New FileStream(...)
Using ms as MemoryStream = Util.StreamUtils.CopyStream(fs)
'For loop here with your setting variations
ms.Seek(0, SeekOrigin.Begin)
'Place upload and resize code here
'End Loop
End Using
End Using
The following code snippet should do what you want:
Using myImage = Image.FromFile(fullImg)
Using ms As New MemoryStream()
myImage.Save(ms, ImageFormat.Jpeg)
ms.Seek(0, SeekOrigin.Begin)
UploadImage(ms, SKU)
End Using
End Using
As an aside, you might find it easier to parameterize your methods and do all the work when calling them. Something like the following may make your life easier (this assumes the code you posted is code you are actually using and not a demo):
Public Shared Sub UploadImages()
'Call this for each image
MoveToAmazon("C:\ImageLocation\blah.jpg", "OriginalImage", 300, 300, 0, "whatever")
End Sub
Public Shared Sub MoveToAmazon(strImg As String, targetFolder As String, height as Integer, width as Integer, padding as Integer, SKU As String)
Dim fullImg As String = "" & strImg
Using img = Image.FromFile(fullImg)
'Here Im missing the code to convert it to a stream.
Using ms As New MemoryStream()
Image.Save(ms, ImageFormat.Jpeg)
ms.Seek(0, SeekOrigin.Begin)
UploadImage(ms, SKU)
End Using
End Using
End Sub
Public Shared Sub UploadImage(imgStream As Stream, imgName As String, targetFolder As String, height as Integer, width as Integer, padding as Integer, SKU As String)
Dim c As New ImageResizer.Configuration.Config
ImageResizer.ImageBuilder.Current.Build(SourceMain, imgStream, New ResizeSettings("width=" & CStr(width) & "&height=" & CStr(height) & "&scale=both&paddingWidth=" & CStr(padding))
AmazonUploadFile(targetFolder & "/" & imgName, imgStream)
End Sub
Public Shared Sub AmazonUploadFile(S3Key As String, FileStream As Stream)
Dim request As New PutObjectRequest()
request.WithBucketName(BUCKET_NAME)
request.WithKey(S3Key).InputStream = FileStream
request.WithCannedACL(S3CannedACL.PublicRead)
GetS3Client.PutObject(request)
End Sub
Using ms As New MemoryStream()
Image.Save(ms, ImageFormat.Jpeg)
ms.Seek(0, SeekOrigin.Begin)
UploadImage(ms, SKU)
End Using
Read the image bytes and then you wrap it in a MemoryStream
MemoryStream ms = new MemoryStream(imageBytes);