I am creating a PDF using iTextSharp and trying to add an image in the header of the PDF. The code is like this
public override void OnOpenDocument(PdfWriter writer, Document document)
{
image = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/Content/images/HSBC/hsbc.png"));
image.ScaleAbsoluteHeight(25);
image.ScaleAbsoluteWidth(134);
image.SetAbsolutePosition(38, 800);
}
Note : The actual image size is height:25px and width:134px. That's what i am giving in the the image.ScaleAbsoluteHeight(25) and image.ScaleAbsoluteWidth(134) respectively.
But i don't understand why the image becomes large when PDF generated and it's look awful.
Thanks
You have to change your code like :
var imagepath = Server.MapPath("~/Images/logo.jpg");
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath);
image.SetAbsolutePosition(440, 10);
image.ScaleToFit(120f, 155.25f);
This will definitely work for you.
Cheers !!
Related
I need to save the whole of a DataGridView as an Image.
I have seen some post online but it did not work for me.
So far, I've tried these 2 links:
DataGridView to Bimap and Save Image in folder.
What I intend is that once a Button is pressed, the DataGridView will be converted into an Image and it will be automatically saved to the Desktop.
The code I'm using generates an error:
A generic error occurred in GDI+
private void button1_Click(object sender, EventArgs e)
{
//Resize DataGridView to full height.
int height = dataGridView1.Height;
dataGridView1.Height = dataGridView1.RowCount * dataGridView1.RowTemplate.Height;
//Create a Bitmap and draw the DataGridView on it.
Bitmap bitmap = new Bitmap(this.dataGridView1.Width, this.dataGridView1.Height);
dataGridView1.DrawToBitmap(bitmap, new Rectangle(0, 0, this.dataGridView1.Width, this.dataGridView1.Height));
//Resize DataGridView back to original height.
dataGridView1.Height = height;
//Save the Bitmap to folder.
bitmap.Save(#"C:\\Desktop\\datagrid.jpg");
}
Hope to get some help. Thanks!
You need to fix more than one section of you code:
bitmap.Save(#"C:\\Desktop\\datagrid.jpg");. This path string should be:
#"C:\Users\SomeUser\Desktop\datagrid.jpg"
or
"C:\\Users\\SomeUser\\Desktop\\datagrid.jpg"`
See point 6.
When calculating the DataGridView height, you're not including the grid's Header.
When creating a Bitmap object, that object must be disposed of, as any other disposable object you create. You can use the Bitmap.Dispose() method or declare your object with a using statement (preferred).
Bitmap.Save([Path]), without specifying an ImageFormat, creates a PNG image. The file extension you insert in the Path string is not considered. At this time, you're creating a file with a .jpg extension when it's actually a .png file.
You should use the Png format, not Jpeg when saving this kind of bitmap. Its loss-less compression is more adeguate: it will preserve the image colors and improve the overall quality.
The Path to the current user Desktop should not be hard-coded. This path is returned by Environment.SpecialFolder.Desktop.
You could modify your code as follows:
using System.IO;
private void button1_Click(object sender, EventArgs e)
{
int DGVOriginalHeight = dataGridView1.Height;
dataGridView1.Height = (dataGridView1.RowCount * dataGridView1.RowTemplate.Height) +
dataGridView1.ColumnHeadersHeight;
using (Bitmap bitmap = new Bitmap(dataGridView1.Width, dataGridView1.Height))
{
dataGridView1.DrawToBitmap(bitmap, new Rectangle(Point.Empty, dataGridView1.Size));
string DesktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
bitmap.Save(Path.Combine(DesktopFolder, "datagridview1.png"), ImageFormat.Png);
}
dataGridView1.Height = DGVOriginalHeight;
}
try this
image save file path , like this "C:\Users\User\Desktop\datagrid.jpg"
bitmap.Save(#"C:\Users\User\Desktop\datagrid.jpg");
Try Replacing bitmap.Save(#"C:\\Desktop\\datagrid.jpg"); with :
File.WriteAllBytes(#"C:\\Desktop\\datagrid.jpg", (byte[])new ImageConverter().ConvertTo(bitmap, typeof(byte[])));
The code below creates a new PDF with landscape orientation. It uses ABCPdf component.
static void Main(string[] args)
{
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "da.pdf");
var theDoc = new Doc();
//theDoc.Read(filePath);
// apply a rotation transform
theDoc.MediaBox.String = "Legal";
double w = theDoc.MediaBox.Width;
double h = theDoc.MediaBox.Height;
double l = theDoc.MediaBox.Left;
double b = theDoc.MediaBox.Bottom;
theDoc.Transform.Rotate(90, l, b);
theDoc.Transform.Translate(w, 0);
// rotate our rectangle
theDoc.Rect.Width = h;
theDoc.Rect.Height = w;
// add some text
theDoc.Rect.Inset(50, 50);
theDoc.FontSize = 96;
theDoc.AddText("Landscape Orientation");
theDoc.AddPage();
theDoc.PageNumber = theDoc.PageCount;
theDoc.AddText("Page 2");
// adjust the default rotation and save
int theID = theDoc.GetInfoInt(theDoc.Root, "Pages");
theDoc.SetInfo(theID, "/Rotate", "90");
theDoc.Save(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "out.pdf"));
theDoc.Clear();
}
Instead of creating new pdf, I would like to open an existing PDF and change the orientation of a specific page to landscape using ABCPdf. like 1st page will be in Portrait and 2nd will be on Landscape.
Thanks
You can do so, or use "AddImageDoc" method, to insert a modified page...
BUT
Abcpdf doesn't allow to overwrite the source file. From "Save Method Documentation":
ABCpdf operates an intelligent just-in-time object loading scheme
which ensures that only those objects that are required are loaded
into memory. This means that if you are modifying large documents then
server load will be kept to a minimum. The original PDF document must
be available for as long as the Doc object is being used.
As a result you cannot modify or overwrite a PDF file while it is read
into a Doc object. You will need to save your PDF to another location
and then swap the two files around after the Doc object's use of the
PDF is ended (with a call to Clear, Dispose, or Read with another PDF
file).
So you will need always a "new pdf".
i am using BarcodeInter25 class to make barcode. I am able to make it but its just blur how can it become more sharp ??
also its background white colour is not completely white
My Code:
BarcodeInter25 code25 = new BarcodeInter25();
Rectangle r = new iTextSharp.text.Rectangle(38, 152);
code25.ChecksumText = false;
code25.Code = "some digits";
code25.BarHeight = 2
System.Drawing.Image i = code25.CreateDrawingImage(System.Drawing.Color.Black, System.Drawing.Color.White);
MemoryStream ms = new MemoryStream();
i.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Image img = Image.GetInstance(ms.ToArray());
ms.Dispose();
Looking at your code, it should be obvious why the barcode is blurry. You convert it to a System.Drawing.Image (making it a raster image) and then you convert it to an iTextSharp.text.Image (but by then the image is already blurry).
The correct way to achieve what you want, is to create an iTextSharp.text.Image straight from the barcode (do not pass through System.Drawing.Image). This can be done like this:
BarcodeInter25 code25 = new BarcodeInter25();
Rectangle r = new iTextSharp.text.Rectangle(38, 152);
code25.ChecksumText = false;
code25.Code = "some digits";
code25.BarHeight = 2;
PdfContentByte cb = writer.DirectContent;
Image img = code25.CreateImageWithBarcode(cb, null, null);
Now the Image object won't be a raster image (with pixels that make the lines blurry), but it will be a true vector image (no pixels, but instructions such as moveTo(), lineTo() and stroke()). Vector data has the advantage that it is resolution independent: you can zoom in and zoom out as much as you want, it will always be sharp.
This is explained in Chapter 10 of my book where you'll find the Barcodes example. In that chapter, you'll also discover the setFont() (or in iTextSharp the Font property). I quote from the API documentation:
public void setFont(BaseFont font)
Sets the text font.
Parameters:
font - the text font. Set to null to suppress any text
So if you don't want to see any text, you can add the following line to the above code snippet:
code25.Font = null;
You should avoid re-sizing by any means. The output is most likely pixel-perfect but when you scale it up/down a bilinear filter will smooth it rendering it blurry.
I had the same exact problem by embedding a QRC code in a PDF and solved it by avoiding a resize.
If you really need a different size apply it programmatically in code by using the correct interpolation algorithm.
I need a method or library that convert a image jpg to file pdf. I tried find in web, but I did find only the SautinSoft, but this is to pdf to jpg and is not free.
Can someone help me?
This function is for C# 3.5.
What you need is a library to create PDFs, like http://www.pdfsharp.net/
Then you can create a pdf document and inject your image into it. You're not looking to convert a JPG to a PDF, that doesn't make much sense, you're trying to create a PDF with your JPG inside it.
Sample code from another answer: Overlay image onto PDF using PDFSharp
private void GeneratePDF(string filename, string imageLoc)
{
PdfDocument document = new PdfDocument();
// Create an empty page or load existing
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
DrawImage(gfx, imageLoc, 50, 50, 250, 250);
// Save and start View
document.Save(filename);
Process.Start(filename);
}
void DrawImage(XGraphics gfx, string jpegSamplePath, int x, int y, int width, int height)
{
XImage image = XImage.FromFile(jpegSamplePath);
gfx.DrawImage(image, x, y, width, height);
}
I have two images and I want to convert it to one pdf file with one image in a page...
what is the easiest way of doing it in C#?
Edit: I tried the following code (added the PdfSharp reference):
string source1 = #"MySource1.JPG";
string source2 = #"MySource2.JPG";
string destinaton = #"MyDest.pdf";
PdfDocument doc = new PdfDocument();
doc.Pages.Add(new PdfPage());
doc.Pages.Add(new PdfPage());
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
XImage img = XImage.FromFile(source1);
XGraphics xgr2 = XGraphics.FromPdfPage(doc.Pages[1]);
XImage img2 = XImage.FromFile(source2);
xgr.DrawImage(img, 0, 0);
xgr2.DrawImage(img2, 0, 0);
doc.Save(destinaton);
doc.Close();
Now it is create a pdf with my two pages but the problem now is that the images are cut and not in their original size! the size of the pictures is 3264x2448.
How can I fix the image size to the pdf document size?
There are several overloads of DrawImage. Use an overload that allows you to specify the destination size of the image.
Three lines of code allow to calculate the image size to use the complete page (with a margin if wanted) while keeping the aspect ratio.
If you know the pdf document size, you can resize your image as:
Bitmap objBitmap = new Bitmap(objImage, new Size(size1, size2));
where objImage is your original image.
or like:
public static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
objBitmap = resizeImage(objBitmap, new Size(size1,size2));