I have a previously created PDF file.
I want to add a stamp to it with Cyrillic characters and a frame.
For example
For this i use iTextSharp 5.5.13.3
I can make a rectangle, but when I want to add text, I get an error:
System.ArgumentException: 'windows-1252' is not a supported encoding
name. For information on defining a custom encoding, see the
documentation for the Encoding.RegisterProvider method. (Parameter
'name')
Code that does this:
PdfTemplate layer2 = appearance.GetLayer(2);
String text = " Копия ВЕРНА\n"
+ " Дата: " + DateTime.Now.ToString("dd.MM.yyyy HH:mm") +"\n";
string externalFont = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "Arial.TTF");
BaseFont externalBaseFont = BaseFont.CreateFont(externalFont, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); **Throws an exception here!**
Font font = new Font(externalBaseFont,6, Font.NORMAL, BaseColor.BLACK);
float size = font.Size;
float margin = 1;
Rectangle dataRect = new Rectangle(margin, margin, appearance.Rect.Width- margin, appearance.Rect.Height - margin);
if (size <= 0)
{
Rectangle sr = new Rectangle(dataRect.Width, dataRect.Height);
size = ColumnText.FitText(font, text, sr, 10, appearance.RunDirection);
}
ColumnText ct = new ColumnText(layer2);
ct.RunDirection=(appearance.RunDirection);
ct.SetSimpleColumn(new Phrase(text, font), dataRect.Left, dataRect.Bottom, dataRect.Right, dataRect.Top, size, Element.ALIGN_LEFT);
ct.Go();
layer2.SetRGBColorStroke(0, 0, 0);
layer2.SetLineWidth(0.5);
layer2.Rectangle(dataRect.Left, dataRect.Bottom, dataRect.Width, dataRect.Height);
layer2.Stroke();
The solution to my problem was adding:
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding.GetEncoding("windows-1252");
before reading the pdf
using (PdfReader reader = new PdfReader(unsignedPdf))
{
...
}
Related
I have a font that supports line drawing characters above 127.
When I try to embed those characters in the .pdf they are removed.
Is there anyway i can force iTextSharp to use the font to display those characters?
So far i have this;
BaseFont bf = BaseFont.CreateFont("font.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
StreamReader reader = new StreamReader(args[0]);
PdfContentByte cb = writer.DirectContent;
cb.SetColorFill(BaseColor.BLACK);
cb.SetFontAndSize(bf, 32);
cb.SetCharacterSpacing(2);
cb.BeginText();
float y = starty;
var line = "\u0094";
while ((line = reader.ReadLine()) != null)
{
cb.ShowTextAligned(Element.ALIGN_LEFT, line, 0, y, 0);
y -= 32;
}
cb.EndText();
reader.Close();
Sample of the text I am trying to embed;
ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
³ Some text ³
ÃÄÄÄÄÄÄÄÄÂÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ´
Thanks in advance for any help.
I am trying to make a orders page and there i have added a button which fetches some data and i am trying to display that data in pdf file and generate a pdf file. the data is being displayed correctly but i cant get the watermark on pdf.
here's the code
using (MemoryStream stream = new MemoryStream())
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
DrawWatermark(page, font);
XGraphics gfx = XGraphics.FromPdfPage(page);
string total = "Total price: " + ord.Totalprice;
string remark = "Remark: " + ord.Remark;
string status = "Payment status: " + ord.PaymentStatus;
gfx.DrawString(total, font, XBrushes.Black, 10, 100);
gfx.DrawString(remark, font, XBrushes.Black, 10, 135);
gfx.DrawString(status, font, XBrushes.Black, 10, 170);
document.Save(stream, false);
return File(stream.ToArray(), "application/pdf", "Invoice.pdf");
}
another method
void DrawWatermark(PdfPage page, XFont font)
{
string watermark = "CartMart";
// Variation 2: Draw a watermark as an outlined graphical path.
// NYI: Does not work in Core build.
// Get an XGraphics object for drawing beneath the existing content.
var gfx1 = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
// Get the size (in points) of the text.
var size = gfx1.MeasureString(watermark, font);
// Define a rotation transformation at the center of the page.
gfx1.TranslateTransform(page.Width / 2, page.Height / 2);
gfx1.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
gfx1.TranslateTransform(-page.Width / 2, -page.Height / 2);
// Create a graphical path.
var path = new XGraphicsPath();
// Create a string format.
var format = new XStringFormat();
format.Alignment = XStringAlignment.Near;
format.LineAlignment = XLineAlignment.Near;
// Add the text to the path.
// AddString is not implemented in PDFsharp Core.
path.AddString(watermark, font.FontFamily, XFontStyle.BoldItalic, 150,
new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2),
format);
// Create a dimmed red pen.
var pen = new XPen(XColor.FromArgb(128, 255, 0, 0), 2);
// Stroke the outline of the path.
gfx1.DrawPath(pen, path);
gfx1.Dispose();
}
there is no watermark in pdf file. can somebody help me with the code. i want to display data as well and i dont know whats going on. There is no error as well.
Seems you mixed up a bit variations 2 and 3 from here. In variation 2, you should use XGraphicsPdfPageOptions.Prepend to draw beneath instead of above.
Also, if you're using .NET Core, it seems only variation 1 works. Looks like there is a port for Core here but no idea what is the status of this development.
I'm trying to write some text to a background image and save it as PDF, I'm using iTextSharp and the following Code:
var image = System.Drawing.Image.FromFile("resources\\bg2.png");
Document document = new Document();
var pageSize = new iTextSharp.text.Rectangle((1122*75)/100, (793 * 75) / 100);
document.SetPageSize(pageSize);
iTextSharp.text.Image bg = iTextSharp.text.Image.GetInstance(image,System.Drawing.Imaging.ImageFormat.Png);
bg.Alignment = iTextSharp.text.Image.UNDERLYING;
var writter = PdfWriter.GetInstance(document, new FileStream("file.pdf", FileMode.OpenOrCreate));
document.Open();
document.Open();
bg.SetAbsolutePosition(0, 0);
document.NewPage();
document.Add(bg);
BaseFont Tajawal = BaseFont.CreateFont(#"Resources\Tajawal-Medium 500.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Paragraph paragraphTable1 = new Paragraph();
paragraphTable1.SpacingAfter = 15;
PdfContentByte cb = writter.DirectContent;
PdfPTable table = new PdfPTable(1);
table.DefaultCell.NoWrap = false;
table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
table.TotalWidth = (image.Width - (image.Width / 3));
table.AddH1(#"شهادة", new iTextSharp.text.Font(Tajawal));
table.WriteSelectedRows(0, -1, 60, 420, cb);
document.Close();
and the Method for AddH1 is as following:
public static void AddH1(this PdfPTable table, string Text, iTextSharp.text.Font tajawal)
{
tajawal.Size = 26f;
tajawal.SetStyle(iTextSharp.text.Font.BOLD);
Phrase ph = new Phrase(Text, tajawal);
PdfPCell text = new PdfPCell(ph);
text.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
text.Padding = 6;
text.Border = 0;
text.NoWrap = false;
text.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
table.AddCell(text);
}
My problem is if I use Tajawal font some of the characters are missing, like the last letter, if i use Tahoma font it works as expected, I'm thinking it might be a problem with encoding, any one faced this before ?
if i use the same font on word, or HTML it works perfectly, one thing to notice here is that Arabic letters can be presented in a separated way or joined together, what i figured out is all characters will not be displayed if typed in separated way, it would only work if its joined.
If i open Character Map i found out the following:
Characters starting from U+0621 to U+0649 are separated form (Does not work)
Characters starting from U+FE82 to U+FEFC are joined form (Works Perfectly)
I'm signing a document with token certificate:
var cp = new Org.BouncyCastle.X509.X509CertificateParser();
var chain = new[] { cp.ReadCertificate(cert.RawData) };
var externalSignature = new X509Certificate2Signature(cert, "SHA-1");
var pdfReader = new PdfReader(origem);
var signedPdf = new FileStream(destino, FileMode.Create);
var pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0');
var sig = pdfStamper.SignatureAppearance;
sig.SetVisibleSignature(new Rectangle(50, 0, 500, 50), pdfReader.NumberOfPages, "Signature");
sig.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
sig.Layer2Text = "Assinado digitalmente por " + cert.SubjectName.Name;
sig.Layer2Font = new Font(Font.FontFamily.TIMES_ROMAN, 7);
MakeSignature.SignDetached(sig, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
The signature text is rendered at bottom of the page. How can I change to a vertical mode, in the right part of document, outside the content margins?
thanks
First of all, to get some vertically oriented signature, the rectangle in which to visualize the signature should be somewhat more vertically oriented. Thus, in place of your
sig.SetVisibleSignature(new Rectangle(50, 0, 500, 50), pdfReader.NumberOfPages, "Signature");
you should use something like
sig.SetVisibleSignature(new Rectangle(50, 0, 50, 500), pdfReader.NumberOfPages, "Signature");
Now you clarified in comments that not only the visualization rectangle should have a vertical orientation but that the text also should be drawn vertically. iText by default creates visualizations with horizontal text. Thus, you have to use customized appearances.
As I am more at home with iText/Java, this example to customize a PdfSignatureAppearance appearance is in Java. It should be easy to transform to iTextSharp/C#, though.
appearance.setVisibleSignature(rectangle, PAGENUMBER, SIGNATURENAME);
// customize appearance layer 2 to display text vertically
PdfTemplate layer2 = appearance.getLayer(2);
layer2.transform(new AffineTransform(0, 1, -1, 0, rectangle.getWidth(), 0));
Font font = new Font();
font.setColor(BaseColor.WHITE);
font.setSize(10);
ColumnText ct2 = new ColumnText(layer2);
ct2.setRunDirection(PdfWriter.RUN_DIRECTION_NO_BIDI);
ct2.setSimpleColumn(new Phrase("Signed by me, myself and I", font), 0, 0, rectangle.getHeight(), rectangle.getWidth(), 15, Element.ALIGN_CENTER);
ct2.go();
This example draws "Signed by me, myself and I" vertically in the page area rectangle.
public bool drawVerticalText(string _text, Color _color, int _angle, int _size, int _left, int _top)
{
try
{
BaseColor bc = new BaseColor(_color.R, _color.G, _color.B, _color.A);
PdfContentByte cb = writer.DirectContent;
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
//int width = baseFont.GetWidth(_text);
cb.BeginText();
cb.SetColorFill(CMYKColor.RED);
cb.SetFontAndSize(bf, _size);
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, _text, _left, document.Top - _top, _angle);
cb.EndText();
document.Close();
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
You can change the alpha value of the color, rotation angle (say, 45), text size and make a watermark to your document...
While above method uses DirectContent with absolute coordinates, the below method uses cell object with rotation property. Note that cell rotation can be multiple of 90, while with the 1st method you can have any angle...
public void drawVerticalText2()
{
PdfPTable table = new PdfPTable(4);
float[] widths = new float[] { 1.25f, 1.55f, 0.35f, 0.35f };
table.SetWidths(widths);
PdfPCell horizontalCell = new PdfPCell(new Phrase("I'm horizontal"));
horizontalCell.Border = BORDERS.BOX;
horizontalCell.HorizontalAlignment = 1;
table.AddCell(horizontalCell);
PdfPCell horizontalMirroredCell = new PdfPCell(new Phrase("I'm horizontal mirrored"));
horizontalMirroredCell.Border = BORDERS.BOX;
horizontalMirroredCell.HorizontalAlignment = 1;
horizontalMirroredCell.Rotation = 180;
table.AddCell(horizontalMirroredCell);
PdfPCell verticalCell = new PdfPCell(new Phrase("I'm vertical"));
verticalCell.Border = BORDERS.BOX;
verticalCell.HorizontalAlignment = 1;
verticalCell.Rotation = 90;
table.AddCell(verticalCell);
PdfPCell verticalMirroredCell = new PdfPCell(new Phrase("I'm vertical mirrored"));
verticalMirroredCell.Border = BORDERS.BOX;
verticalMirroredCell.HorizontalAlignment = 1;
verticalMirroredCell.Rotation = -90;
table.AddCell(verticalMirroredCell);
table.SpacingBefore = 20f;
table.SpacingAfter = 30f;
document.Add(table);
document.Close();
}
enjoy!
Hi
I want to add a text in persian language (a right to left language) to the top of an existing pdf file, using iTextSharp Version 5.0.0.0 library.
I use this code:
public static void InsertText(string SourceFileName, string TargetFileName, string Text, int x, int y)
{
PdfReader reader = new PdfReader(SourceFileName);
Document document = new Document(PageSize.A4, 0, 0, 0, 0); // open the writer
FileStream fs = new FileStream(TargetFileName, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
PdfContentByte cb = writer.DirectContent; // select the font properties
FontFactory.RegisterDirectories();
Font fTahoma = FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 10, Font.NORMAL, BaseColor.RED);
writer.SetMargins(0, 0, 0, 0);
ColumnText ct = new ColumnText(writer.DirectContent);
ct.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
Phrase p = new Phrase(Text, fTahoma);
ct.SetText(p);
ct.SetSimpleColumn(x, y, x + 350, y + 20);
ct.Go();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
cb.AddTemplate(page, 0, 0); // close the streams and voilá the file should be changed :)
document.NewPage();
}
document.Close();
fs.Close();
writer.Close();
}
I call InsertText("Source.pdf", "Target.pdf", "Persian message", 10, 800);
My source.pdf page size is: height: 842, width: 595
Unfortunately i get target.pdf with only half of my message! The other vertical half is hidden!
Now the question is: How i can add a right to left language text to the top of an existing pdf file?
Problem: The imported page is probably overwriting the text.
Solution: Add your PdfImportedPage, THEN add the text.