C# iTextSharp characters above 127 removed (Line drawing) - c#

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.

Related

iTextSharp how to add Cyrillic font in PDF document

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))
{
...
}

Arabic Watermark phrase issue in iTextSharp

I'm trying to print watermark using iTextSharp in c#
But in Arabic phrase it displays separated and reverse letter
I try multiple solutions like this :
public void AddWaterMark(PdfWriter writer , Document document , BaseFont baseFont , float x , float y , PdfPCell PdfPInfoCell)
{
float fontsize = 40;
float angle = 45;
try
{
string fontpath = HttpContext.Current.Server.MapPath("~/path/fonts/arial.ttf");
BaseFont BaseArabicFont = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, true);
iTextSharp.text.Font HeaderArabicFont = new iTextSharp.text.Font(BaseArabicFont, 10);
Paragraph BaseInfoParagraph = new Paragraph();
PdfContentByte under = writer.DirectContentUnder;
var gstate = new PdfGState { FillOpacity = 0.1f, StrokeOpacity = 0.3f };
Phrase p3 = new Phrase("السلام عليكم", HeaderArabicFont);
PdfPTable PdfTable = new PdfPTable(10);
PdfTable.WidthPercentage = 100;
PdfTable.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
PdfTable.AddCell(PdfPInfoCell);
under.SaveState();
under.SetGState(gstate);
under.BeginText();
under.SetColorFill(BaseColor.LIGHT_GRAY);
under.SetFontAndSize(baseFont, fontsize);
under.ShowTextAligned(PdfContentByte.LINE_CAP_PROJECTING_SQUARE, p3[0].Chunks[0].Content, x, y, angle);
under.EndText();
under.RestoreState();
//document.Close();
}
catch (Exception ex)
{
return;
}
}
the output is :
م ك ي ل ع م ا ل س ل ا
So kindly I need your support

Writing Arabic Text to PDF using ITextSharp

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)

Send output from SSRS as PDF direct to printer

I am trying to get the out put from SSRS export and send it direct to a Server side printer without calling a print Dialog
ReportingService.ReportExporter.Export("basicHttpEndpoint", new NetworkCredential("userNmae", "*********"), reportName, parameters.ToArray(), reportFormat, out output, out extension, out mimeType, out encoding, out warnings, out streamIds);
In this case the export type is an Image; I am trying to get the output (which is a Byte Array) and setting a Memory stream and then trying to print directly using PrintDocumen() as follows
Stream stream = new MemoryStream(output);
StreamReader streamToPrint = new StreamReader(stream);
var pd = new PrintDocument();
pd.PrintPage += pd_PrintPage;
pd.PrintController = new StandardPrintController();
pd.Print();
The pd_PrintPage is well documented onthe web and MSDN
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
string line = null;
// Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height /
printFont.GetHeight(ev.Graphics);
// Print each line of the file.
while (count < linesPerPage &&
((line = streamToPrint.ReadLine()) != null))
{
yPos = topMargin + (count *
printFont.GetHeight(ev.Graphics));
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
count++;
}
// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}
I am not able to get the format of the data, it just prints the image data as characters. DO I need to convert the output data to another format?
Becasue you're telling the print command to brint the bytes as text instead of rendering the output. In order to render the stream to the printer you need a PDF print driver (e.g. Acrobat). Here are some options:
https://stackoverflow.com/questions/8338953/print-in-memory-pdf-without-saving-directly-without-a-printer-dialog-or-user-i
Printing a PDF in c# using a stream ... can it be done ?

Add right to left language text to the custom position of existing pdf file by iTextSharp

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.

Categories

Resources