I have used pdfSharp to insert text into PDF file but when I use font Times New Roman bold, there are some problems.
Here is my code :
using PdfSharp.Pdf;
using PdfSharp.Drawing;
PdfSharp.Pdf.PdfDocument pdf = new PdfSharp.Pdf.PdfDocument();
pdf.Info.Title = filePrint;
PdfSharp.Pdf.PdfPage pdfPage = pdf.AddPage();
pdfPage.Size = PdfSharp.PageSize.A4;
using (XGraphics graph = XGraphics.FromPdfPage(pdfPage))
{
XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
XFont fontBold = new XFont("Times New Roman", 10, XFontStyle.Bold, options);
graph.DrawString("Đây là đoạn text bold", fontBold, XBrushes.Black, new XRect(75.6, 56, 30, 30), XStringFormats.TopLeft);
}
Then my result is like this:
Please help me to find solution for this error.
You can use additionnaly MigraDoc.
Following this article :
Can you try this :
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using (var document = new PdfDocument())
{
PdfPage page = document.AddPage();
XGraphics graph = XGraphics.FromPdfPage(page);
graph.MUH = PdfFontEncoding.Unicode;
graph.MFEH = PdfFontEmbedding.Always;
// You always need a MigraDoc document for rendering.
Document doc = new Document();
Section section = doc.AddSection();
Font font = new Font("Times New Roman", 12);
foreach (var line in textFileLines)
{
Paragraph paragraph = section.AddParagraph();
paragraph.AddFormattedText(line, font);
}
//save pdf document
PdfDocumentRenderer renderer = new PdfDocumentRenderer();
renderer.Document = doc;
renderer.RenderDocument();
renderer.Save(output);
}
Related
This was my code for itextsharp which worked ok. It displayed "Quote Only" in the middle of each page in a pdf file.
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(Server.MapPath(#"~\Content\WaterMarkQuoteOnly.png"));
PdfReader readerOriginalDoc = new PdfReader(File(all, "application/pdf").FileContents);
int n = readerOriginalDoc.NumberOfPages;
img.SetAbsolutePosition(0, 300);
PdfGState _state = new PdfGState()
{
FillOpacity = 0.1F,
StrokeOpacity = 0.1F
};
using (MemoryStream ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(readerOriginalDoc, ms, '\0', true))
{
for (int i = 1; i <= n; i++)
{
PdfContentByte content = stamper.GetOverContent(i);
content.SaveState();
content.SetGState(_state);
content.AddImage(img);
content.RestoreState();
}
}
//return ms.ToArray();
all = ms.GetBuffer();
}
This is my new itext 7 code, this also displays the watermark but the position is wrong. I was dismayed to see that you cant add an image to the canvas but you have to add ImageData when the position is being set on the image. The image is also way smaller and back to front.
var imagePath = Server.MapPath(#"~\Content\WaterMarkQuoteOnly.png");
var tranState = new iText.Kernel.Pdf.Extgstate.PdfExtGState();
tranState.SetFillOpacity(0.1f);
tranState.SetStrokeOpacity(0.1f);
ImageData myImageData = ImageDataFactory.Create(imagePath, false);
Image img = new Image(myImageData);
img.SetFixedPosition(0, 300);
var reader = new PdfReader(new MemoryStream(all));
var doc = new PdfDocument(reader);
int pages = doc.GetNumberOfPages();
using (var ms = new MemoryStream())
{
var writer = new PdfWriter(ms);
var newdoc = new PdfDocument(writer);
for (int i = 1; i <= pages; i++)
{
//get existing page
PdfPage page = doc.GetPage(i);
//copy page to new document
newdoc.AddPage(page.CopyTo(newdoc)); ;
//get our new page
PdfPage newpage = newdoc.GetPage(i);
Rectangle pageSize = newpage.GetPageSize();
//get canvas based on new page
var canvas = new PdfCanvas(newpage);
//write image data to new page
canvas.SaveState().SetExtGState(tranState);
canvas.AddImage(myImageData, pageSize, true);
canvas.RestoreState();
}
newdoc.Close();
all = ms.GetBuffer();
ms.Flush();
}
You are doing something strange with the PdfDocument objects, and you are also using the wrong AddImage() method.
I am not a C# developer, so I rewrote your example in Java. I took this PDF file:
And I took this image:
Then I added the image to the PDF file using transparency with the following result:
The code to do this, was really simple:
public void createPdf(String src, String dest) throws IOException {
PdfExtGState tranState = new PdfExtGState();
tranState.setFillOpacity(0.1f);
ImageData img = ImageDataFactory.create(IMG);
PdfReader reader = new PdfReader(src);
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(reader, writer);
for (int i = 1; i <= pdf.getNumberOfPages(); i++) {
PdfPage page = pdf.getPage(i);
PdfCanvas canvas = new PdfCanvas(page);
canvas.saveState().setExtGState(tranState);
canvas.addImage(img, 36, 600, false);
canvas.restoreState();
}
pdf.close();
}
For some reason, you created two PdfDocument instances. This isn't necessary. You also used the AddImage() method passing a Rectangle which resizes the image. Also make sure that you don't add the image as an inline image, because that bloats the file size.
I don't know which programming language you are using. For instance: I am not used to variables that are created using var such as var tranState. It should be very easy for you to adapt my Java code though. It's just a matter of changing lowercases into uppercases.
Using the following code to create a PDF document in C# using iText 5. The text does not render in the courier font. Why not?
private void SimpleFontDoc(string pdfDocPath)
{
Document doc = new Document(PageSize.LETTER, 10, 10, 42, 30);
var fs = new FileStream(pdfDocPath, FileMode.Create);
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
doc.Open();
string[] lines = new string[]
{
"First text line",
"Second text line"
};
var font = FontFactory.GetFont("courier", 12.0f, BaseColor.BLACK);
foreach (var line in lines)
{
var para = new iTextSharp.text.Paragraph(line);
para.Font = font;
doc.Add(para);
}
doc.Close();
}
In iText5 you have to specify the font before adding text to the Paragraph element (or alternatively pass it to the constructor).
Change
var para = new iTextSharp.text.Paragraph(line);
para.Font = font;
into
var para = new iTextSharp.text.Paragraph(line, font);
i tried using iTextSharp to get the text from a pdf document,
it works great if the pdf file is with english text(latin chars).
If i try to get the text from a pdf doc with cyrillic characters the output is just question marks. Are there some settings to be made, or cyrillic isnt supported?
this is the code for creating the pdf:
string testText = "зззi";
string tmpFile = #"C:\items\test.pdf";
string myFont = #"C:\windows\fonts\verdana.ttf";
iTextSharp.text.Rectangle pgeSize = new iTextSharp.text.Rectangle(595, 792);
iTextSharp.text.Document doc = new iTextSharp.text.Document(pgeSize, 10, 10, 10, 10);
iTextSharp.text.pdf.PdfWriter wrtr;
wrtr = iTextSharp.text.pdf.PdfWriter.GetInstance(doc,
new System.IO.FileStream(tmpFile, System.IO.FileMode.Create));
doc.Open();
doc.NewPage();
iTextSharp.text.pdf.BaseFont bfR;
bfR = BaseFont.CreateFont(myFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
iTextSharp.text.BaseColor clrBlack =
new iTextSharp.text.BaseColor(0, 0, 0);
iTextSharp.text.Font fntHead =
new iTextSharp.text.Font(bfR, 34, iTextSharp.text.Font.NORMAL, clrBlack);
iTextSharp.text.Paragraph pgr =
new iTextSharp.text.Paragraph(testText, fntHead);
doc.Add(pgr);
doc.Close();
this is the code for retrieving the text:
PdfReader reader1
= new PdfReader("c:/items/test.pdf");
Console.WriteLine(PdfTextExtractor.GetTextFromPage(reader1, 1, new SimpleTextExtractionStrategy()));
Console.ReadLine();
the output is: ???i
EDIT 2
i managed to read text from the pdf i created, but still cant get the text from a random pdf. How can i check if that pdf provides the required info for text extraction?
iTextSharp doesn't display Japanese font. I found a solution but when I compile, I get an error saying:
Font 'STSong-Light' with 'UniGB-UCS2-H' is not recognized.
Here's my source code:
BaseFont.AddToResourceSearch(serverPath + "\\lib\\iTextAsian.dll");
BaseFont.AddToResourceSearch(serverPath + "\\lib\\iTextAsianCmaps.dll");
BaseFont font = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
using (Document document = new Document())
{
using (PdfSmartCopy copy = new PdfSmartCopy(
document, new FileStream(directoryOutPdf + nameOutPdf, FileMode.Create))
)
{
document.Open();
// generate one page per statement
for (int i = 0; i < countBlank.Count; i++)
{
// replace this with your PDF form template
PdfReader reader = new PdfReader(pdfTemplatePath + #"\EmptyTemplateBankBlank_2012.pdf");
using (var ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(reader, ms))
{
AcroFields form = stamper.AcroFields;
form.SetFieldProperty("Info", "textfont", font, null);
form.SetField("Info", "_源泉徴収票");
stamper.FormFlattening = true;
}
reader = new PdfReader(ms.ToArray());
copy.AddPage(copy.GetImportedPage(reader, 1));
}
}
}
}
I think it's because I didn't install the STSong-Light font. Unfortunately I could not find STSong-Light and, therefore, had to set Stsong font, but it still does not work.
String fontPath = Path.Combine(serverPath + "\\Fonts", "STSONG.ttf");
BaseFont baseFont = BaseFont.CreateFont(fontPath, "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font font = new Font(baseFont, 12, Font.NORMAL);
Set the SubstitutionFont after creating the PdfStamper:
stamper.AcroFields.AddSubstitutionFont(myFont.BaseFont);
I was in need of the ability to create a PDF Envelope, and hadn't found a good solution for doing so, so I thought that this might be of some interest.
We use PDFSharp, a free PDF document tool. It worked out pretty well. Here's the method for doing so. It will create a new pdf document, envelope sized, and center the address. GetAddress() is just a method used to retrieve the address from a DB. Just use
\n to newline the different lines in the address.
protected void DisplayPDFEnvelope()
{
try
{
PdfDocument document = new PdfDocument();
PdfPage pdfpage = new PdfPage();
XUnit pdfWidth = new XUnit(4.125, XGraphicsUnit.Inch);
XUnit pdfHeight = new XUnit(9.5, XGraphicsUnit.Inch);
pdfpage.Height = pdfHeight;
pdfpage.Width = pdfWidth;
pdfpage.Orientation = PageOrientation.Landscape;
XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
document.AddPage(pdfpage);
// Create a font
XFont font = new XFont("ARIAL", 1, XFontStyle.Regular, options);
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(pdfpage, XGraphicsPdfPageOptions.Append);
string address = GetAddress();
// Get the size (in point) of the text
XSize size = gfx.MeasureString(address, font);
// Create a graphical path
XGraphicsPath path = new XGraphicsPath();
path.AddString(address, font.FontFamily, XFontStyle.Regular, 10,
new XPoint(345, 160), XStringFormats.Default);
// Create a dimmed pen and brush
XPen pen = new XPen(XColor.FromGrayScale(0), 0);
XBrush brush = new XSolidBrush();
// Stroke the outline of the path
gfx.DrawPath(pen, brush, path);
MemoryStream stream = new MemoryStream();
document.Save(stream, false);
Page.Response.Clear();
Page.Response.ContentType = "application/pdf";
Page.Response.AppendHeader("Content-Length", stream.Length.ToString());
Page.Response.AppendHeader("Content-Type", "application/pdf");
Page.Response.AppendHeader("Content-Disposition", "inline;filename=envelope.pdf");
Page.Response.BinaryWrite(stream.ToArray());
Page.Response.Flush();
stream.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
throw ex;
}
}
PDFSharp is good, so is iTextSharp, the Java port of iText, one of the first PDF libraries around.