I am using the code below to generate a pdf. Is there a way I can point to an image and use that as the header? "~/images/Header.png"? Any help would be appreciated. Thank you.
Dim myUniqueFileName = String.Format("{0}.pdf", random)
Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(Doc1, New FileStream(path & myUniqueFileName, FileMode.Create))
Dim ev As New itsEvents
pdfWrite.PageEvent = ev
Doc1.Open()
Dim test As String
test = Session("PDF")
Doc1.Add(New Paragraph(test))
Doc1.Close()
End Sub
Public Class itsEvents
Inherits PdfPageEventHelper
Public Overrides Sub OnStartPage(ByVal writer As iTextSharp.text.pdf.PdfWriter, ByVal document As iTextSharp.text.Document)
Dim ch As New Chunk("This is my Header on page " & writer.PageNumber)
document.Add(ch)
End Sub
End Class
Try this:
Dim imagepath As String = Server.MapPath(".") & "/logo/Anjanlogo.jpg"
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imagepath)
image.ScalePercent(24F)
doc.Add(image)
Note: The 24F scaling comes from the fact that, by default, embedded images are 72 DPI and most commercial printers use 300 DPI, so 72/300 * 100 = 24%.
To move the image around the page you can use the SetAbsolutePosition method, like this:
image.SetAbsolutePosition(36F, 36F)
Note: 36F is the margin of the PDF, so this will push the logo to the top left of the corner of the PDF, but still maintain the border.
Related
I am trying to implement an image download in vb.net where the client clicks a button and the browser downloads an image for the client from a file in the server.
I tried this:
Private Sub DownloadImage(ByVal ImageURL As String)
Dim Buffer(6000000) As Byte
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=" & ImageURL & ".jpg")
Response.ContentType = "image/jpeg"
Response.BinaryWrite(Buffer)
Response.Flush()
Response.End()
End Sub
But this has 2 problems. First, it doesn't actually show up the image when I download it so it doesn't work properly. Secondly I have to manually enter the size of the image to determine the size of the byte array.
Please help me out, I couldn't find any resources on internet and couldn't get my head around it.
Thanks!
This is a sample image handler I've used for several years. It's probably got some room for improvement, but it is intended to be used as the src attribute for an img tag.
<img src="Thumbs.ashx?img=/ImagePath/BigImage.jpg&max=100" />
It's a direct copy-paste of my working code and it's got some references to private code - but it should give you a good start. It will create a thumbnail image so it doesn't have to be regenerated each time, if the thumbnail has already been generated. Hope this helps...
<%# WebHandler Language="VB" Class="GetImage" %>
Imports Web.Utilities
Imports Common
Imports System
Imports System.Drawing
Imports System.Web
Imports System.IO
''' <summary>
''' Resizes the image supplied in the "img" querystring parameter and writes it to the OutputStream in jpg format.
''' The default dimension is a max of 90 pixels (H or W; whichever is larger).
''' The "max" querystring parameter can alter the maximum dimension by supplying a new dimension as an integer.
''' If the file name contains an ampersand, it should be replaced with [amp].
''' </summary>
''' <remarks></remarks>
Public Class GetImage : Implements IHttpHandler
Private thumbFolder As String = "/images/Thumbs/"
Private trapCount As Integer = 0
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'General.PreventClientCaching()
'context.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim maxSize As Integer = 90
Dim img As String = context.Request.QueryString("img")
Dim strMax As String = context.Request.QueryString("max")
If Not strMax.IsNullOrEmpty AndAlso IsNumeric(strMax) Then
maxSize = CInt(strMax)
End If
If maxSize > 1000 Then
maxSize = 1000
End If
If img.IsNullOrEmpty Then
img = "/images/PicUnavailable.jpg"
End If
Try
Dim uri As New System.Uri(img, UriKind.RelativeOrAbsolute)
img = uri.AbsolutePath
Catch ex As Exception
End Try
General.SetContentType(General.FileType.Jpg)
img = img.Replace("[amp]", "&")
ServeImage(context, img, maxSize)
End Sub
Private Sub ServeImage(ByVal context As HttpContext, ByVal imagePath As String, ByVal maximumSize As Integer)
Dim imgFile As Image = Nothing
Dim existingThumb As String = imagePath.Replace("/", "{s}") & "_" & maximumSize.ToString & ".jpg"
Dim doPurge As Boolean
Boolean.TryParse(context.Request.QueryString("purge"), doPurge)
' Check to see if the thumbnail has already been generated and it's older than the source.
' If it is, delete it.
If File.Exists(context.Server.MapPath(thumbFolder & existingThumb)) Then
If doPurge Then
File.Delete(context.Server.MapPath(thumbFolder & existingThumb))
Else
If File.GetLastWriteTime(context.Server.MapPath(thumbFolder & existingThumb)) < File.GetLastWriteTime(context.Server.MapPath(imagePath)) Then
Try
File.Delete(context.Server.MapPath(thumbFolder & existingThumb))
Catch ex As Exception
End Try
End If
End If
End If
' If the thumbnail already exists, write the byte array to the output stream
If File.Exists(context.Server.MapPath(thumbFolder & existingThumb)) Then
Dim fs As FileStream = Nothing
Try
fs = New FileStream(context.Server.MapPath(thumbFolder & existingThumb), IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Dim imgLen As Long = fs.Length()
Dim imgData(imgLen) As Byte
fs.Read(imgData, 0, Integer.Parse(imgLen.ToString()))
context.Response.OutputStream.Write(imgData, 0, Integer.Parse(imgLen.ToString()))
Catch ex2 As UnauthorizedAccessException
'context.Server.Transfer(img)
Throw
Catch exIO As IOException
'context.Server.Transfer(img)
Throw
Finally
If Not fs Is Nothing Then
fs.Dispose()
fs = Nothing
End If
End Try
' the file doesn't exist, so render it to the output stream and save it to the thumbnail
Else
Try
imgFile = Image.FromFile(context.Server.MapPath(imagePath))
Dim maxDim As Integer = maximumSize
Dim maxH As Integer = maximumSize
Dim maxW As Integer = maximumSize
'If img.Height > maxH OrElse img.Width > maxW Then
Dim thumb As Image
Dim gfx As Graphics
Dim rect As Rectangle
If imgFile.Height >= imgFile.Width Then 'portrait or square
Dim newW As Integer
newW = CInt((maxH / imgFile.Height) * imgFile.Width)
thumb = New Bitmap(newW, maxDim)
gfx = Graphics.FromImage(thumb)
gfx.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
gfx.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
gfx.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
rect = New Rectangle(0, 0, newW, maxDim)
Else 'landscape
Dim newH As Integer
newH = CInt((maxW / imgFile.Width) * imgFile.Height)
thumb = New Bitmap(maxDim, newH)
gfx = Graphics.FromImage(thumb)
gfx.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
gfx.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
gfx.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
rect = New Rectangle(0, 0, maxDim, newH)
End If
gfx.DrawImage(imgFile, rect)
thumb.Save(context.Response.OutputStream, Drawing.Imaging.ImageFormat.Jpeg)
thumb.Save(context.Server.MapPath(thumbFolder & existingThumb), Drawing.Imaging.ImageFormat.Jpeg)
gfx.Dispose()
thumb.Dispose()
gfx = Nothing
thumb = Nothing
Catch ex As Exception
Dim fs As FileStream = Nothing
Try
fs = New FileStream(context.Server.MapPath(imagePath), IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Dim imgLen As Long = fs.Length()
Dim imgData(imgLen) As Byte
fs.Read(imgData, 0, Integer.Parse(imgLen.ToString()))
context.Response.OutputStream.Write(imgData, 0, Integer.Parse(imgLen.ToString()))
Catch ex2 As UnauthorizedAccessException
'context.Server.Transfer(img)
Throw
Catch exIO As IOException
'context.Server.Transfer(img)
If trapCount > 0 Then
Throw
End If
trapCount += 1
ServeImage(context, "/images/PicUnavailable.jpg", maximumSize)
Finally
If Not fs Is Nothing Then
fs.Dispose()
fs = Nothing
End If
End Try
Finally
If Not imgFile Is Nothing Then
imgFile.Dispose()
imgFile = Nothing
End If
End Try
End If
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
I have the following code:
Dim data As Byte() = CType(oSDR("SIGNIMAGE"), Byte())
Dim ms As New MemoryStream(data)
Dim img As Image = Image.FromStream(ms)
Image1.Visible = Convert.ToInt32(Image.FromStream(ms))
ms.Dispose()
ms.Close()
this is code with <asp:image>. I want to show image with listview or literal from the databse.
I hope masters can help me..provide example about my question
thanks
regards
arif
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
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);
I just noticed it last night,
Anyway, let's get to the interesting case here.
I have a ButtonField within DataGrid, and if you notice it here...
The Interface of that ButtonField is looks like a LINK.
But if we hover on it, it appeared as Javascript's call.
Here is the Image ScreenShot
Ya, that's the 1st case.
IT IS a javascript's call.
I didnt notice about it lately. (hehehe).
Then, if we click on that... it would call the createPDF() function. The function behind the scene (which I'm using VB.net) is to execute these code;
Protected Sub createPDF()
Dim document As New Document()
Dim mem As LengthFixingStream = New LengthFixingStream()
' instantiate a iTextSharp.text.pdf.Document
'Dim mem As New MemoryStream()
' PDF data will be written here
PdfWriter.GetInstance(document, mem)
' tie a PdfWriter instance to the stream
document.Open()
Dim titleFont = FontFactory.GetFont("Arial", 18, Font.BOLD)
document.Add(New Paragraph("Northwind Traders Receipt", titleFont))
document.Close()
' automatically closes the attached MemoryStream
Dim docData As Byte() = mem.GetBuffer()
' get the generated PDF as raw data
' write the document data to response stream and set appropriate headers:
Response.AppendHeader("Content-Disposition", "attachment; filename=testdoc.pdf")
Response.ContentType = "application/pdf"
Response.BinaryWrite(docData)
Response.[End]()
End Sub
But somehow... this of course would not deliver the PDF into the browser.
BEcause It's called by Javascript, nor the direct as Hyperlink (normally).
Thus, I'm wondering could we get the ASP.net Call new Window,
and then redirect the createPDF() result into it?
Correct me if i'm wrong...
Here is just some mockup so you get the idea. I haven't tested this. Basically you will have to put the above code in a new page...say "receipt.aspx" and execute it on the load event...you will need to setup an id parameter...if data is being pulled from the db to generate the pdf.
on the button click add the following
Dim sb As New System.Text.StringBuilder()
sb.Append("<script language='javascript'>")
sb.Append("window.open('receipt.aspx.htm?id=123'', 'Receipt',")
sb.Append("'width=800, height=800, menubar=yes, resizable=no');<")
sb.Append("/script>")
Dim t As Type = Me.GetType()
If Not ClientScript.IsStartUpScriptRegistered(t, "PopupScript") Then
ClientScript.RegisterStartUpScript(t, "PopupScript", sb.ToString())
End If
Notice the "id=123" querystring value I am passing to receipt.aspx?
You can then call that in the receipt.aspx page like this
Dim id as String = Request.QueryString("id")
CreatePDF(id)
...shoot! Just realized you are using a Grid...the principle remains the same, just wireup the buttons on RowDataBound event.
Protected Sub GridView_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim Id As String = DirectCast(e.Row.Cells(0).FindControl("quotationid"), Label).Text
Dim myButton As New Button
myButton = DirectCast(e.Row.Cells(4).FindControl("btnViewReceipt"), Button)
myButton.Attributes.Add("OnClick", "window.open('receipt.aspx?id=" + id + "','Receipt','scrollbars=yes','width=800,height=800')")
End If
End Sub