iTextSharp BarcodeEAN 13 change width - c#

I'm using iTextSharp to create EAN13 barcodes, but I can't change the width of the generated barcode. :(
Changing the height works fine with BarHeight = x
System.Drawing.Image bm = code39.CreateDrawingImage(Color.Black, Color.White);
BarcodeEAN codeEan = new BarcodeEAN();
codeEan.CodeType = Barcode.EAN13;
codeEan.Code = "4035606872510";
codeEan.BarHeight = 130f;
codeEan.X = ... //not working
codeEan.Size = ... //also not working
bm = codeEan.CreateDrawingImage(Color.Black, Color.White);
bm.Save("D:\\temp\\foo.png", ImageFormat.Png);
/* Resizing only stretches the pixels with bad quality */
iTextSharp.text.Image barcode = iTextSharp.text.Image.GetInstance(bm, ImageFormat.Png);
barcode2.ScaleToFit(1200f, 130f);

Found a solution by myself....
But for people with the same problem:
Document doc = new Document();
MemoryStream memStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memStream);
writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
writer.CompressionLevel = PdfStream.BEST_COMPRESSION;
doc.Open();
PdfContentByte cb = writer.DirectContent;
BarcodeEAN codeEan = new BarcodeEAN();
codeEan.GenerateChecksum = true;
codeEan.CodeType = Barcode.EAN13;
codeEan.Code = "5449000101549";
codeEan.Font = null;
iTextSharp.text.Image imageEAN = codeEan.CreateImageWithBarcode(cb, null, null);
imageEAN.ScaleAbsolute(150, 50);
imageEAN.SetAbsolutePosition(doc.PageSize.Right - 186f, doc.PageSize.Bottom + 30f);
doc.Add(imageEAN);
...

Related

how create pdf after image Draw c#

I'm working with PdfSharp to create some pdf files
I am trying to write an image after that save pdf and force download user
but after show box to download and open file, pdf was empty
var foo = new PrivateFontCollection();
foo.AddFontFile(HttpContext.Current.Server.MapPath("~/assets/css/base/fonts/Coustom.ttf"));
var Font_6 = new Font((FontFamily)foo.Families[0], 6f);
StringFormat rf = new StringFormat();
rf.LineAlignment = StringAlignment.Far;
rf.Alignment = StringAlignment.Far;
Brush _RedColor = new SolidBrush(Color.FromArgb(63, 110, 123));
System.Drawing.Image imgBackground = System.Drawing.Image.FromFile(Server.MapPath("../assets/EmptyDoc/Letterhead-FA-A4.jpg"));
int _X = 2300;
int _Y = 450;
using (Graphics graphics = Graphics.FromImage(imgBackground))
{
graphics.DrawString("TEST", Font_6, _RedColor, new PointF((_X - 40), (_Y)), rf);
}
imgBackground.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
byte[] fileContents = null;
MemoryStream memoryStream = new MemoryStream();
document.Save(memoryStream, true);
fileContents = memoryStream.ToArray();
Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=TEST.pdf");
Response.BinaryWrite(fileContents);
With PdfSharp, you can add an image as the following :
using (FileStream stream = new FileStream(pngFile, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
XImage image = XImage.FromStream(stream);
XGraphics graphics = XGraphics.FromPdfPage(this.currentPage);
graphics.DrawImage(image, 0 , 0, 200, 100);
}
you just need to replace pngFile by the full path of your drawing file.
Edit :
After reading your code, you could try to add this after the line XGraphics gfx = XGraphics.FromPdfPage(page); :
XImage image = XImage.FromStream(strm);
XGraphics graphics = XGraphics.FromPdfPage(page);
graphics.DrawImage(image, 0 , 0, 200, 100);
Then replace
imgBackground.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
by
MemoryStream strm = new MemoryStream();
imgBackground.Save(strm, System.Drawing.Imaging.ImageFormat.Png);
Seems the function doesn't accept your Stream, so try with a MemoryStream

Add Watermark image to PDF

I'm trying to add watermark to pdf aready exist in a folder inside my project, I'm using iTextSharp.
Everything is going well and debugging the code is going well, but when finished and I try to open the PDF with watermark just worked on, the file is damage.
Here is my piece of code
string sourceFilePath = Server.MapPath(#"~/uploadfiles/PDFFileName.pdf");
byte[] bytes = File.ReadAllBytes(sourceFilePath);
Bitmap bitmap = new Bitmap(200, 30, System.Drawing.Imaging.PixelFormat.Format64bppArgb);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.Clear(Color.White);
graphics.DrawString(text, new System.Drawing.Font("Arial", 12, FontStyle.Bold), new SolidBrush(Color.Red), new PointF(0.4F, 2.4F));
bitmap.Save(Server.MapPath("~/uploadfiles/Image.jpg"), ImageFormat.Jpeg);
bitmap.Dispose();
var img = iTextSharp.text.Image.GetInstance(Server.MapPath("~/uploadfiles/Image.jpg"));
img.SetAbsolutePosition(200, 400);
PdfContentByte waterMark;
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
PdfStamper stamper = new PdfStamper(reader, stream);
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
waterMark = stamper.GetUnderContent(i);
waterMark.AddImage(img);
}
bytes = stream.ToArray();
}
File.Delete(Server.MapPath("~/uploadfiles/Image.jpg"));
File.WriteAllBytes(sourceFilePath, bytes);

Change pageSize of pdf before saving

I receive a pdf as a byte[]. When I save this binary as pdf, pageSize is too big. I want to change the pageSize in the code.
Currently I am trying it this way, based on what I found in other questions:
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using (MemoryStream stream = new MemoryStream(pdfAsBinary))
{
using (PdfReader reader = new PdfReader(pdfAsBinary))
{
using (Document doc = new Document(PageSize.A4))
{
PdfWriter writer = PdfWriter.GetInstance(doc, stream);
PdfImportedPage page = writer.GetImportedPage(reader, 1);
image = Image.GetInstance(page);
using (var pdfStream = new FileStream(tempPath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
{
PdfWriter pdfwriter = PdfWriter.GetInstance(doc, pdfStream);
doc.Open();
doc.SetPageSize(PageSize.A4);
image.ScalePercent(30f);
doc.Add(image);
doc.Close();
}
}
}
File.Copy(tempPath, pathToFile);
}
Or I tried using this method:
private static byte[] resizeToA4(byte[] inputDoc)
{
using (MemoryStream out = new MemoryStream())
{
using (PdfReader reader = new PdfReader(inputDoc))
{
using (Document doc = new Document(PageSize.A4))
{
PdfWriter writer = PdfWriter.GetInstance(doc, out);
}
}
return outPDF.ToArray();
}
None of the above is working and it feels like I'm overcomplicating things. How can I achieve my resizing of the pageSize to A4?
This method works for one-page-files.
public static void ScaleToA4self(byte[] pdfAsBinary, string locationOfPdfOut)
{
PdfReader reader = new PdfReader(pdfAsBinary);
Rectangle originalSize = reader.GetPageSize(1);
float originalHeight = originalSize.Height;
float originalWidth = originalSize.Width;
Rectangle newSize = PageSize.A4;
float newHeight = newSize.Height;
float newWidth = newSize.Width;
float scaleHeight = newHeight / originalHeight;
float scaleWidth = newWidth / originalWidth;
Document doc = new Document(newSize, 0, 0, 0, 0);
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(locationOfPdfOut, FileMode.Create));
doc.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, scaleWidth, 0, 0, scaleHeight, 0, 0);
doc.Close();
}

itextsharp insert text in pdf file with C#

I want to insert text into a pdf file with iTextSharp using the code below. Many times it works right but other times it does not work.
FileStream pdfOutputFile = new FileStream(pdfTemplate, FileMode.Create);
PdfReader pdfReader = new PdfReader(pdffile, System.Text.Encoding.UTF8.GetBytes("ownerPassword"));
PdfStamper pdfStamper = null;
// pdfReader.Permissions = 1;
pdfStamper = new PdfStamper(pdfReader, pdfOutputFile);
AcroFields testForm = pdfStamper.AcroFields;
PdfContentByte pdfPageContents = pdfStamper.GetUnderContent(index + 1);
string[] formattext = printTxt.Split(new char[] { '\n' });
float lhight = 0;
float abxt = abx;
printTxt= "Hello word";
ft = new FormattedText(printTxt, Color.Black, "Arial", EncodingType.Winansi, true, 9);
Bitmap b = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(b);
Font f = new Font("Arial", 9);
pdfPageContents.BeginText();
BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, "ASCII", false);
pdfPageContents.SetFontAndSize(baseFont,20); // 40 point font
pdfPageContents.SetRGBColorFill(0, 0, 0);
float textAngle = 0;
pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, printTxt, abx+3, (float)aby + 12 + lhight, textAngle);
pdfPageContents.EndText();
The approach I use to write text on any Pdf file is that I create text fields using a software tool PDF Nitro Professional (You can use some other software to create these fields). Once done you can then use the following pattern of code to write text on those fields.
string pdfTemplate = filePath;
string newFile = outputFilePath;
PdfReader PDFWriter = new PdfReader(pdfTemplate);
PdfStamper pdfStampDocument = new PdfStamper(PDFWriter, new FileStream(newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStampDocument.AcroFields;
//For Text field
pdfFormFields.SetField("txtTextFieldName", "First Text");
//For Check Box Field
pdfFormFields.SetField("chkSomeCheckBox", "Yes");
PDFWriter.Close();
pdfStampDocument.Close();
Hope it helps.

Overlay text over an image background and convert to PDF

Using .NET, I want to programmatically create a PDF which simply consists of a background image with two labels over it with different fonts and positioning. I have read about existing PDF libraries, but don't know (if applicable) which one is the easiest for such a simple task.
Anyone care to guide me?
P.D.: I do not want to create the PDF with a generated image that already overlays the text over the background image.
Edit: This is the final working code:
public string Create()
{
if (!Directory.Exists(ApplicationImagePath))
{
Directory.CreateDirectory(ApplicationImagePath);
}
// Smart card
var doc = new Document(PageSize.GetRectangle("153 242.65"), 0, 0, 0, 0);
using (var stream = File.Create(filepath))
{
var writer = PdfWriter.GetInstance(doc, stream);
doc.Open();
var image = Image.GetInstance(CarnetData.Frame, ImageFormat.Png);
image.Alignment = Element.ALIGN_CENTER;
image.ScaleToFit(153, 242.65f);
doc.Add(image);
BaseFont font = BaseFont.CreateFont(GetFontPath(CarnetConfiguration.FontType), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
font.PostscriptFontName = CarnetConfiguration.FontType.ToString();
float verticalPosition = writer.GetVerticalPosition(false);
var pName = new Paragraph(CarnetData.Name, new Font(font, FontData.EmployeeFont.SizeInPoints))
{
SpacingBefore = verticalPosition - 51f,
MultipliedLeading = 1.1f,
Alignment = Element.ALIGN_CENTER
};
doc.Add(pName);
var pDepartment = new Paragraph(CarnetData.Department, new Font(font, FontData.DepartmentFont.SizeInPoints))
{
SpacingBefore = 1.5f,
MultipliedLeading = 1.2f,
Alignment = Element.ALIGN_CENTER
};
doc.Add(pDepartment);
writer.ViewerPreferences = PdfWriter.PageModeUseNone + PdfWriter.CenterWindow + PdfWriter.PageLayoutSinglePage;
doc.Close();
}
return filepath;
}
Thanks for the help. :)
iTextSharp is a great library you could use, very simple and intuitive:
var doc = new Document();
using (var stream = File.Create("output.pdf"))
{
var writer = PdfWriter.GetInstance(doc, stream);
doc.Open();
doc.Add(Image.GetInstance(#"c:\foo\test.png"));
var cb = writer.DirectContent;
cb.BeginText();
cb.SetTextMatrix(100, 220);
var font = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
cb.SetFontAndSize(font, 12);
cb.ShowText("Hello World");
cb.EndText();
cb.BeginText();
cb.SetTextMatrix(100, 250);
cb.ShowText("Some other text");
cb.EndText();
doc.Close();
}
Use iTextSharp. Free.
#binaryhowl - You can try Syncfusion PDF. It is great component with excellent support
http://asp.syncfusion.com/sfaspnetsamplebrowser/9.1.0.20/Web/Pdf.Web/samples/4.0/

Categories