Add image using itextsharp - image

I am trying to export data in PDF and now i try to add image in PDF using itext sharp i try this but this shows an error ..Is try below code but this shows an error when i add image in PDF file i successfully add text
Private Sub ExportGridToPDF()
Dim headerText As String = "file"
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
GridView1.AllowPaging = False
GridView1.DataBind()
GridView1.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim pdfDoc As New iTextSharp.text.Document(iTextSharp.text.PageSize.A1, 10.0F, 10.0F, 10.0F, 0.0F)
Dim beginning As New iTextSharp.text.Chunk(headerText)
Dim p1 As New iTextSharp.text.Phrase(beginning)
Dim p2 As New iTextSharp.text.Phrase()
p2.Add(p1)
Dim p As New iTextSharp.text.Paragraph()
p.Add(p2)
Dim htmlparser As New HTMLWorker(pdfDoc)
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
pdfDoc.Add(p)
Dim im As Image = iTextSharp.text.Image.GetInstance(imagepath + "/mikesdotnetting.tif")
pdfDoc.Add(im)
htmlparser.Parse(sr)
pdfDoc.Close()
Response.Write(pdfDoc)
Response.End()
End Sub
in this part
Dim im As Image = iTextSharp.text.Image.GetInstance(imagepath + "/mikesdotnetting.tif")
pdfDoc.Add(im)
and this shows an error in this line
Dim jpg As Image = iTextSharp.text.Image.GetInstance(New Uri(url))
error
**Value of type 'iTextSharp.text.Image' cannot be converted to 'System.Web.UI.WebControls.Image'.**
Any Solution?

You are using two classes named Image from a different package / namespace in the same code. That is ambiguous. You should use fully qualified names.
I'm not a .Net developer, but if this were Java, you'd do something like this:
Dim im As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imagepath + "/mikesdotnetting.tif")
Your problem is caused by the fact that you create a variable jpg that is of type System.Web.UI.WebControls.Image, but you are assigning an object of type iTextSharp.text.Image to that variable. It is obvious that this doesn't work.
When you have two classes with the same name (Image) in two different namespaces System.Web.UI.WebControls and iTextSharp.text, you should avoid introducing ambiguities.
Read Resolving an ambiguous reference for more info.

Related

Calling PdfSharp xImg = XImage.FromFile(myImage) immediatly after Bitmap.Save(myImage, ImageFormat.Jpeg)

Good afternoon,
testing a my Window form application I noted an unexpected beaviour when coupling PdfSharp xImg = XImage.FromFile(myImage) with a preceding Bitmap.Save(myImage, ImageFormat.Jpeg).
Briefly:
I create a Bitmap from say 195202_000.jpg and then I save it as xxxx.jpg;
I create the Ximage.FromFile(xxxx.jpg) and add it to a Pdf in creation;
I create another Bitmap this time from 195202_001.jpg and I save it using again the name xxxx.jpg. No problems of overwriting occur.
I create the Ximage.FromFile(xxxx.jpg) and add it to the Pdf in creation;
I save the Pdf.
Well: at the end, xxxx.jpg contains correctly 195202_001.jpg, the Pdf file contains correctly two pages, but the Issue is that both the two pages contain 195202_000.jpg !!!
I do not understand where this issue raises.
If I change the name of the saved bitmap at every step (say xxxx1.jpg, xxxx2.jpg) all is fine.
Thanks for any help.
Paolo.
I attach the rough code used for producing and analizing the issue.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim pdf As New PdfDocument
Dim fArray(1) As String
'TWO images.jpg PathName in array
fArray(0) = "C:\Users\Administrator\Desktop\myTestInp\195202_000.jpg"
fArray(1) = "C:\Users\Administrator\Desktop\myTestInp\195202_001.jpg" `
'Looping the array: creat bitmap from each image in fArray(), draw and save it as a new jpg,
'immediatly(re - Load) the new jpeg for adding it to a Pdf.
'Issue that I noted occurs when using the same PathName for saving and re-loading the image.
'Please see below.
For i As Integer = 0 To 1
'CREATE BitmapInp from fArray(i)
Dim BitmapInp As Bitmap = New Bitmap(fArray(i))
'DRAW BitmapOut
Dim BitmapOut As New Bitmap(BitmapInp.Width, BitmapInp.Height)
Dim grBitmapOut = Graphics.FromImage(BitmapOut)
grBitmapOut.DrawImage(BitmapInp, 0, 0, BitmapInp.Width, BitmapInp.Height)
grBitmapOut.Dispose()
BitmapInp.Dispose()
'SAVE BitmapOut as "C:\Users\Administrator\Desktop\myTestOut\xxxx.jpg"
'NOTE: each time, the Bitmap is saved using the same file name above.
'overwriting does not raise errors.
BitmapOut.Save("C:\Users\Administrator\Desktop\myTestOut\xxxx.jpg", ImageFormat.Jpeg)
BitmapOut.Dispose()
'LOAD BitmapOut as xImg from "C:\Users\Administrator\Desktop\myTestOut\xxxx.jpg"
'NOTE: FromFile just saved
Using xImg = XImage.FromFile("C:\Users\Administrator\Desktop\myTestOut\xxxx.jpg")
Dim page = pdf.AddPage()
Dim grPdf = PdfSharp.Drawing.XGraphics.FromPdfPage(page)
page.Width = 500 * 72 / xImg.HorizontalResolution
page.Height = 500 * 72 / xImg.HorizontalResolution
xImg.Interpolate = False
grPdf.DrawImage(xImg, 0, 0, page.Width, page.Height)
End Using
Next
'END of loop
'SAVE Pdf
pdf.Save("C:\Users\Administrator\Desktop\myTestOut\Dummy.Pdf")
'Issue: the Pdf contains correctly two pages, but they are equals! And precisely is
' the first image that occurs two times!
End Sub
I didn't check the source code of PDFsharp/MigraDoc, but maybe the filename is used as a "unique key" to prevent incorporating multiple copies of the same image into one PDF file.
If the same image is used on multiple pages, only one copy of the image data is included in the file.
I know that PDFsharp tries to prevent multiple copies - and IIRC the filename is the key.
And yes, using different file names should resolve the issue.

VBA download and embed images using url from adjacent cell

I've attempted the solution in the following.
Inserting an Online Picture to Excel with VBA
Unfortunately I get a run-time error '1004'
"Unable to get the Insert property of the Picture class"
which stops on the following code :
Set myPicture = ActiveSheet.Pictures.Insert(pic)
Could this be due to my Office version 2016 (64bit) ?
If not, are there any suggestions of how I might get embed images to adjacent cells in column AK using the image urls from column AJ ?
Thanks in advance
There's some evidence that Excel has trouble downloading from AWS, and I've recreated your issue using the URL you mentioned. In this case, if I were on a deadline I'd put in this fall-back method when the first one fails: download the file, then insert it into the document, then delete the file.
directDownloadFailed:
Dim FileNum As Long
Dim TempFile As String
Dim FileData() As Byte
Dim WHTTP As Object
Set WHTTP = CreateObject("WinHTTP.WinHTTPrequest.5.1")
WHTTP.Open "GET", imgURL, False
WHTTP.Send
FileData = WHTTP.ResponseBody
Set WHTTP = Nothing
FileNum = FreeFile
TempFile = "path\to\save\img.jpg"
Open TempFile For Binary Access Write As #FileNum
Put #FileNum, 1, FileData
Close #FileNum
Set img = ActiveSheet.Pictures.Insert(TempFile)
SetAttr TempFile, vbNormal
Kill TempFile
GoTo resumeProcessingImg
#keydemographic
I appreciate the response and that definitely sounds like an option but I cannot get that code to work or incorporate it into the code I'm using. I get a compile error "Label Not defined" on GoTo resumeProcessingImg
The following will download and embed the images into the cells but the code stops once it gets to the s3 aws image urls.
I'll try a few other ways to incorporate your code but I'm not having much luck with it so far.
This is my test file
Sub URL2IMG()
Dim pic As String 'path of pic
Dim myPicture As Picture 'embedded pic
Dim rng As Range 'range over which we will iterate
Dim cl As Range 'iterator
Set rng = Range("b2:b12") '<~~ as needed, Modify range to where the images are to be embedded.
For Each cl In rng
pic = cl.Offset(0, -1) '<~~ defines image link URL in column to the left of the embedded column
Set myPicture = ActiveSheet.Pictures.Insert(pic)
'you can play with the following to manipulate the size & position of the picture.
With myPicture
.ShapeRange.LockAspectRatio = msoFalse
' currently this shrinks the picture to fit inside the cell.
.Width = cl.Width
.Height = cl.Height
.Top = Rows(cl.Row).Top
.Left = Columns(cl.Column).Left
End With
Next
End Sub

Convert ico file to png Visual Basic

I am Looking for Code in VB that convert Ico File to other Format such as:
Jpg,JPEG,BMP,PNG
someone know such thing like that?
i tried it:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ImageUrl As String
ImageUrl = "C:\Arto.ico"
Dim str As Integer
str = InStr(ImageUrl, ".ico")
If (str > 0) Then
Dim b As New Bitmap(ImageUrl)
Dim newurl = Mid(ImageUrl, 1, Len(ImageUrl) - 4)
newurl = newurl + ".jpg"
b.Save(newurl) <<<<error here
' newurl = Mid()
' b.Save()
End If
End Sub
and that it the error i got:
An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll
Additional information: A generic error occurred in GDI+.
There is no image codec for icons. It is a pretty non-trivial format that can store multiple images and has 3 bitmaps for each image, one that contains the image pixels and two monochrome bitmaps that indicate which pixels are transparent and which are inverted. The Image class just doesn't have the plumbing in place to fully specify the properties that are needed to faithfully generate an .ico file.
But you're ahead since you want a PNG of JPEG file. You can create a bitmap that has the same size as the icon and draw the icon into that bitmap. A very important and non-trivial selection you need to make is choosing a background color for the image. Required because icons have transparency so you'll see the background on which it is displayed. Some image formats, like JPEG, don't support transparency. You have to pick one, Color.White tends to be okayish since that's the common background color for programs that display icons. You can use Color.Transparent for a PNG image.
Sample code:
Dim srce = "c:\temp\test.ico"
Dim dest = "c:\temp\test.jpg"
Using ico = New Icon(srce)
Using bmp = New Bitmap(ico.Width, ico.Height)
Using gr = Graphics.FromImage(bmp)
gr.Clear(Color.White) '' NOTE!
gr.DrawIcon(ico, 0, 0)
End Using
bmp.Save(dest, System.Drawing.Imaging.ImageFormat.Jpeg)
End Using
End Using

Dim Picture1 As PictureBox ? Problem with LoadPicture !

My VB6 Code :
Dim Picture1 As PictureBox
Picture1.Picture = LoadPicture("D:\1538125064shot.jpg")
I am getting the following error on the second line:
91 : Object variable or With block variable not set
Your variable is declared as Picture1, but you try to access it as Picture1v.
Use StdPicture to hold pictures before using them
Dim myPic As StdPicture
Set myPic = LoadPicture("D:\1538125064shot.jpg")
Later you can apply it to a picture box like this
Set Picture1.Picture = myPic

Is there an Alternative to using the LoadPicture("bmp_or_icon_file_path") to loading Images in Excel 2007 VBA

I have an Excel 2007 Worksheet with many buttons and labels that act as menu options (i.e. user clicks the buttons, labels with images) and is presented with forms, or some thing else.
These images / icons for the buttons and labels are loaded in VBA by assigning the Picture property of the Control and calling LoadPicture() method with the full image file path as parameter, like So.
With SomeFormObject
.cmdOpenFile.Picture = LoadPicture("F:\projectname\images\fileopen.BMP")
End With
This method of loading images for buttons, other controls is causing 2 issues.
1) It creates a dependency on the image files and physical location for every user, so if a user does not have the drive mapped and files present, the VBA fails with runtime error of file or path not found.
2)
The app gets very slow if the images are on a shared drive (which is the case)
I want to eliminate both issues and somehow load icons, images into control internally, without any external dependencies on external image files.
What is the best way to achieve this in Excel 2007 VBA?
I could not file any Visual Basic 6.0 / Visual Studio style "Resource File Editor" / feature with which to accomplish this.
Please advice! thank you
-Shiva #
mycodetrip.com
I really hope that there is a easier way to do this, but this is the only one I found:
The Idea is:
You keep the Pictures embedded in a Sheet and every time you want to set the pictures for the Command you export them from your worksheet to a file and load them through LoadPicture. The only way to export an embedded Picture through VBA that I found is by making it a Chart first.
The following code is based on 'Export pictures from Excel' from johnske
Option Explicit
Sub setAllPictures()
setPicture "Picture 18", "CommandButtonOpen"
setPicture "Picture 3", "CommandButtonClose"
End Sub
Sub setPicture(pictureName As String, commandName As String)
Dim pictureSheet As Worksheet
Dim targetSheet As Worksheet
Dim embeddedPicture As Picture
Dim pictureChart As Chart
Dim MyPicture As String
Dim PicWidth As Long
Dim PicHeight As Long
Set pictureSheet = Sheets("NameOfYourPictureSheet") ' <- to Change '
Set targetSheet = Sheets("NameOfYourSheet") ' <- to Change '
Set embeddedPicture = pictureSheet.Shapes(pictureName).OLEFormat.Object
With embeddedPicture
MyPicture = .Name
PicHeight = .ShapeRange.Height
PicWidth = .ShapeRange.Width
End With
Charts.Add
ActiveChart.Location Where:=xlLocationAsObject, Name:=pictureSheet.Name
Set pictureChart = ActiveChart
embeddedPicture.Border.LineStyle = 0
With pictureChart.Parent
.Width = PicWidth
.Height = PicHeight
End With
With pictureSheet
.Select
.Shapes(MyPicture).Copy
With pictureChart
.ChartArea.Select
.Paste
End With
.ChartObjects(1).Chart.Export Filename:="temp.jpg", FilterName:="jpg"
End With
pictureChart.Parent.Delete
Application.ScreenUpdating = True
targetSheet.Shapes(commandName).OLEFormat.Object.Object.Picture = LoadPicture("temp.jpg")
Set pictureChart = Nothing
Set embeddedPicture = Nothing
Set targetSheet = Nothing
Set pictureSheet = Nothing
End Sub
Sub listPictures()
' Helper Function to get the Names of the Picture-Shapes '
Dim pictureSheet As Worksheet
Dim sheetShape As Shape
Set pictureSheet = Sheets("NameOfYourSheet")
For Each sheetShape In pictureSheet.Shapes
If Left(sheetShape.Name, 7) = "Picture" Then Debug.Print sheetShape.Name
Next sheetShape
Set sheetShape = Nothing
Set pictureSheet = Nothing
End Sub
To Conclude:
Loading the Images from a Mapped Networked Drive seems less messy, and there shouldn't be that much of a speed difference.
2 alternatives i can think of: form.img.picture=pastepicture , and = oleobjects("ActiveXPictureName").object.picture.

Resources