Fastest way to save bitmap image to PDF using pdfsharp - image

I need to create a pdf file from several bitmap images. I am currently using the following code:
Dim size As New XSize(0,0)
For k = 0 to theBMPList.Count-1
Dim oPage As New PdfPage()
doc.Pages.Add(oPage)
Dim xgr As XGraphics = XGraphics.FromPdfPage(oPage)
Dim img As XImage = XImage.FromGdiPlusImage(theBMPList(k))
size = new XSize(theBMPList(k).Width, theBMPList(k).Height)
oPage.Height = size.Height
oPage.Width = size.Width
xgr.DrawImage(img, 0,0, size.Width-5, size.Height-5)
Next
This works fine but is very slow. Is there a better/faster way to do this?

Related

iTextSharp : image in cell doesn't expand

Hi I'm using iTextSharp 535 .
I have a table with 4rows and 3 columns with images added into paragraphs as chunks.
The image size has been resized at 640x480 , the cell with the image has a fixed height.
Dim fra As New Phrase()
Dim imageBytes = ResizeImage(Base64Value)
ImageB = iTextSharp.text.Image.GetInstance(imageBytes)
Dim Pimg As New Paragraph(vbCrLf)
Pimg.Add(New Chunk(ImageB, 0, 0, True))
Pimg.Alignment = Element.ALIGN_CENTER
fra.Add(Pimg)
Dim cell2 = New PdfPCell(fra)
cell2.FixedHeight = 320
table.AddCell(cell2)
But I get a strange result: the image doesn't expand in the next page but it is placed small at the end of it.

Why I am unable to change the QR Code's size in iText7?

How to change QR Code size?
using (iText.Kernel.Pdf.PdfReader _pdf_reader =
new iText.Kernel.Pdf.PdfReader("tmp/example.pdf"))
{
using (iText.Kernel.Pdf.PdfDocument pdfDoc = new iText.Kernel.Pdf.PdfDocument(_pdf_reader, new iText.Kernel.Pdf.PdfWriter("tmp/output.pdf").SetSmartMode(true)))
{
BarcodeQRCode qrc = new BarcodeQRCode("https://google.com");
PdfFormXObject xObject = qrc.CreateFormXObject(ColorConstants.BLACK, pdfDoc);
float _w = pdfDoc.GetPage(1).GetPageSize().GetWidth();
float _h = pdfDoc.GetPage(1).GetPageSize().GetHeight();
PdfCanvas canvas = new PdfCanvas(pdfDoc.GetPage(1));
canvas.SaveState();
canvas.SetFillColor(ColorConstants.LIGHT_GRAY);
//canvas.Rectangle(_w - 90, _h - 90, 100, 100);
canvas.Fill();
canvas.RestoreState();
canvas.AddXObject(xObject, _w - qrc.GetBarcodeSize().GetWidth(), _h - qrc.GetBarcodeSize().GetHeight());
}
}
I try:
qrc.GetBarcodeSize().GetHeight();
qrc.GetBarcodeSize().GetWidth();
it returns 33
I try to set Height & Width to 100 like below:
qrc.GetBarcodeSize().SetHeight(100);
qrc.GetBarcodeSize().SetWidth(100);
and then check the size again, but it keeps returning 33, is it a bug? or Did I miss something?
please help
thanks
Don
I try to set Height & Width to 100 like below:
Actually, you can`t change the QrCode side this way.
In fact, QRcode is an n*n grid where n depends on some parameters as a QR code version and the error correction level.
When generating, iText uses the smallest version that can fit the content. This is version 4 (33*33) in your case.
The easiest way to change the size of QrCode in a document is by using the version of the createFormXObject method which accepts the moduleSide parameter.
float moduleSize = 100/qrc.GetBarcodeSize().GetHeight();
qrc.createFormXObject(foreground, moduleSize, document)
Module size here is size of the barcode`s grid cell (1 by default).
iTxt 7 Qrcode size effected by three parameter in hints, example example for your reference.
//C# code
//Prepare all necessary properties to create the qrcode
IDictionary<EncodeHintType, Object> hints = new Dictionary<EncodeHintType, object>();
//default character set (ISO-8859-1)
hints[EncodeHintType.CHARACTER_SET] = "UTF-8";
//Qrcode Error correction level L,M,Q,H
//default ErrorCorrectionLevel.L
hints[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.L;
//Qrcode minimal version level
//default 4
hints[EncodeHintType.MIN_VERSION_NR] = 6;
string code = "Qrcode content here";
BarcodeQRCode qrcode = new BarcodeQRCode(code, hints);

Add image using itextsharp

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.

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

Rendering smallest possible image size with MVC3 vs Webforms Library

I am in the process of moving a webforms app to MVC3. Ironically enough, everything is cool beans except one thing - images are served from a handler, specifically the Microsoft Generated Image Handler. It works really well - on average a 450kb photo gets output at roughly 20kb.
The actual photo on disk weighs in at 417kb, so i am getting a great reduction.
Moving over to MVC3 i would like to drop the handler and use a controller action. However i seem to be unable to achieve the same kind of file size reduction when rendering the image. I walked through the source and took an exact copy of their image transform code yet i am only achieving 230~kb, which is still a lot bigger than what the ms handler is outputting - 16kb.
You can see an example of both the controller and the handler here
I have walked through the handler source code and cannot see anything that is compressing the image further. If you examine both images you can see a difference - the handler rendered image is less clear, more grainy looking, but still what i would consider satisfactory for my needs.
Can anyone give me any pointers here? is output compression somehow being used? or am i overlooking something very obvious?
The code below is used in my home controller to render the image, and is an exact copy of the FitImage method in the Image Transform class that the handler uses ...
public ActionResult MvcImage()
{
var file = Server.MapPath("~/Content/test.jpg");
var img = System.Drawing.Image.FromFile(file);
var sizedImg = MsScale(img);
var newFile = Server.MapPath("~/App_Data/test.jpg");
if (System.IO.File.Exists(newFile))
{
System.IO.File.Delete(newFile);
}
sizedImg.Save(newFile);
return File(newFile, "image/jpeg");
}
private Image MsScale(Image img)
{
var scaled_height = 267;
var scaled_width = 400;
int resizeWidth = 400;
int resizeHeight = 267;
if (img.Height == 0)
{
resizeWidth = img.Width;
resizeHeight = scaled_height;
}
else if (img.Width == 0)
{
resizeWidth = scaled_width;
resizeHeight = img.Height;
}
else
{
if (((float)img.Width / (float)img.Width < img.Height / (float)img.Height))
{
resizeWidth = img.Width;
resizeHeight = scaled_height;
}
else
{
resizeWidth = scaled_width;
resizeHeight = img.Height;
}
}
Bitmap newimage = new Bitmap(resizeWidth, resizeHeight);
Graphics gra = Graphics.FromImage(newimage);
SetupGraphics(gra);
gra.DrawImage(img, 0, 0, resizeWidth, resizeHeight);
return newimage;
}
private void SetupGraphics(Graphics graphics)
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighSpeed;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighSpeed;
}
If you don't set the quality on the encoder, it uses 100 by default. You'll never get a good size reduction by using 100 due to the way image formats like JPEG work. I've got a VB.net code example of how to set the quality parameter that you should be able to adapt.
80L here is the quality setting. 80 still gives you a fairly high quality image, but at DRASTIC size reduction over 100.
Dim graphic As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(newImage)
graphic.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
graphic.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality
graphic.PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
graphic.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
graphic.DrawImage(sourceImage, 0, 0, width, height)
' now encode and send the new image
' This is the important part
Dim info() As Drawing.Imaging.ImageCodecInfo = Drawing.Imaging.ImageCodecInfo.GetImageEncoders()
Dim encoderParameters As New Drawing.Imaging.EncoderParameters(1)
encoderParameters.Param(0) = New Drawing.Imaging.EncoderParameter(Drawing.Imaging.Encoder.Quality, 80L)
ms = New System.IO.MemoryStream
newImage.Save(ms, info(1), encoderParameters)
When you save or otherwise write the image after setting the encoder parameters, it'll output it using the JPEG encoder (in this case) set to quality 80. That will get you the size savings you're looking for.
I believe it's defaulting to PNG format also, although Tridus' solution solves that also.
However, I highly suggest using this MVC-friendly library instead, as it avoids all the image resizing pitfalls and doesn't leak memory. It's very lightweight, free, and fully supported.

Resources