Why is my document.Add(paragraph) not working (wpf, iText)? - c#

I am trying to create a pdf using iText in WPF. But I am not able to add any paragraphs to my document.
Here's my code:
string destination = "po.pdf";
var fos = File.Create(destination);
PdfWriter writer = new PdfWriter(fos);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf, PageSize.A4.Rotate());
Paragraph p1 = new Paragraph();
p1.Inlines.Add(new TextBlock()
{
Text = "hello"
});
document.Add(p1);
document.Close();
}
Here, in the second last line (document.Add(p1)), I get a red underline under 'p1'.
The error says --- Cannot convert from 'System.Windows.Documents.Paragraph' to 'iText.Layout.Element.AreaBreak'.
Thank you in advance.

Related

How to create a textbox in word openxml using c#

I am trying to create a textbox using the openxml nuget for a word document. I can't seem to any resources regarding how to add a textbox to my page
Here is what I have tried
using (MemoryStream memory = new MemoryStream())
{
// Create Document
using (WordprocessingDocument wordDocument =
WordprocessingDocument.Create(memory, WordprocessingDocumentType.Document, true))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure and add some text.
mainPart.Document = new Document();
Body docBody = new Body();
TextBox testBox = new TextBox();
TextBoxContent textBoxContent = new TextBoxContent();
Paragraph paragraph = new Paragraph();
Run run = new Run();
Text text = new Text("test");
run.Append(text);
paragraph.Append(run);
textBoxContent.Append(paragraph);
testBox.Append(textBoxContent);
docBody.Append(testBox);
mainPart.Document.Append(docBody);
wordDocument.Save();
}
//Download File
return new MemoryStream(memory.ToArray());
}
The shown code gives me corrupted word error. How am i supposed to append the elements for it to work ?

How to add text to an existing pdf without overwriting the content with iText7 and C#?

I have this piece of code that was supposed to insert a text after an image in a pdf.
// Read the data from input file
string reader = "C:\\InesProjetos\\PrintTextWithImage\\PrintTextWithImage\\cat.pdf";
string dest = "C:\\demo.pdf";
string text = "C:\\InesProjetos\\PrintTextWithImage\\PrintTextWithImage\\text.txt";
StreamReader rdr = new StreamReader(text);
// Must have write permissions
//to the path folder
PdfWriter writer = new PdfWriter(dest);
PdfReader readerFile = new PdfReader(reader);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
document.Add(new Paragraph(rdr.ReadToEnd()));
document.Close();
How do insert the text in text.txt file in cat.pdf file without overwriting the image that is in cat.pdf?
UPDATE
What to do with the readerFile object? Should I insert cat.pdf into demo.pdf and then add the text? And if so how?
Whenever you want to add something to an existing pdf, you have to not only write but also read, i.e. you need both a PdfWriter and a PdfReader for the PdfDocument:
PdfReader reader = new PdfReader(source);
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(reader, writer);
If you furthermore don't want existing content to be covered by new content, you have to tell the objects so, e.g. if you use a Document to add new content:
Document document = new Document(pdf);
document.Add(new AreaBreak(AreaBreakType.LAST_PAGE));
document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
document.Add(new Paragraph(rdr.ReadToEnd()));
document.Close();

Multiple images and texts on same line using iTextSharp

I am trying to create a PDF file on the fly using some backend data and at the bottom of the file I need to include 2 images and a text: a signature image on the left, company logo in the middle and date (underlined with the word "Date" below the line).
I have searched and managed to do two: image on the left and date on the right but now I am stuck trying to get another image in between!
This is what I currently have (assuming I have already read user's name and test date from DB):
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document(PageSize.LETTER.Rotate());
doc.Open();
// Set path to PDF file and images used in the file
string sPath = Server.MapPath("PDF");
string sImagePath = Server.MapPath("assets/Images");
// Set PDF file name
string sFileName = "SomeFileNameGenerated" + ".PDF";
// Open document
PdfWriter myPDFWriter = PdfWriter.GetInstance(doc, ms);
doc.Open();
// Set some font styles
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
Font fntDate = new Font(Font.FontFamily.TIMES_ROMAN, 12f, Font.NORMAL | Font.UNDERLINE, BaseColor.BLACK);
Font fntUserName = new Font(Font.FontFamily.TIMES_ROMAN, 24f, Font.BOLD | Font.UNDERLINE, BaseColor.BLACK);
// Add header image
iTextSharp.text.Image imgHeader = iTextSharp.text.Image.GetInstance(sImagePath + "/headerImage.png");
doc.Add(imgHeader);
iTextSharp.text.Image imgSignature = iTextSharp.text.Image.GetInstance(sImagePath + "/Signature.png");
// Add user's name, underlined, in the center
Paragraph pUserName = new Paragraph(sUserName, fntUserName);
pUserName.Alignment = Element.ALIGN_CENTER;
doc.Add(pUserName);
// Here I am trying to add two images and one date text;
// below I have added one image and one text; need to have another image in between
Paragraph para = new Paragraph();
Phrase ph1 = new Phrase();
Chunk glue = new Chunk(new iTextSharp.text.pdf.draw.VerticalPositionMark());
Paragraph main = new Paragraph();
ph1.Add(new Chunk(imgSignature, 0, 0, true)); // Here I add signature image as a chunk into Phrase.
ph1.Add(glue); // Here I add special chunk to the same phrase.
ph1.Add(new Chunk(sTestDate, fntDate)); // Here I add date as a chunk into same phrase.
main.Add(ph1);
para.Add(main);
doc.Add(para);
doc.Close();
}

getting text from a pdf document itextsharp

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 html to pdf

I want to change some HTML in a pdf. All my html is in HTML string but I don't know how to pass it in correctly within iTextSharp.
public void PDF()
{
// Create a doc object
var doc = new doc(PageSize.A4, 50, 50, 25, 25);
// Create a new PdfWrite object, writing the output to the file ~/PDFTemplate/SimpleFormFieldDemo.pdf
var output = new FileStream(Server.MapPath("t.pdf"), FileMode.Create);
var writer = PdfWriter.GetInstance(doc, output);
// Open the doc for writing
doc.Open();
//Add Wallpaper image to the pdf
var Wallpaper = iTextSharp.text.Image.GetInstance(Server.MapPath("hfc.png"));
Wallpaper.SetAbsolutePosition(0, 0);
Wallpaper.ScaleAbsolute(600, 840);
doc.Add(Wallpaper);
iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(doc);
StyleSheet css = new StyleSheet();
css.LoadTagStyle("body", "face", "Garamond");
css.LoadTagStyle("body", "encoding", "Identity-H");
css.LoadTagStyle("body", "size", "12pt");
hw.Parse(new StringReader(HTML));
doc.Close();
Response.Redirect("t.pdf");
}
If anyone knows how to make this work.. it be good.
Thanks
Dom
Please download The Best iText Questions on StackOverflow. It's a free ebook, you'll benefit from it.
Once you have downloaded is, go to the section entitled "Parsing XML and XHTML".
Allow me to quote from the answer to this question: RowSpan does not work in iTextSharp?
You are using HTMLWorker instead of XML Worker, and you are right:
HTMLWorker has no support for CSS. Saying CSS doesn't work in
iTextSharp is wrong. It doesn't work when you use HTMLWorker, but
that's documented: the CSS you need works in XML Worker.
Please throw away your code, and start anew using XML Worker.
There are many examples (simple ones as well as complex ones) in the book. Let me give you only one:
using (var fsOut = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
using (var stringReader = new StringReader(result))
{
var document = new Document();
var pdfWriter = PdfWriter.GetInstance(document, fsOut);
pdfWriter.InitialLeading = 12.5f;
document.Open();
var xmlWorkerHelper = XMLWorkerHelper.GetInstance();
var cssResolver = new StyleAttrCSSResolver();
var xmlWorkerFontProvider = new XMLWorkerFontProvider();
foreach (string font in fonts)
{
xmlWorkerFontProvider.Register(font);
}
var cssAppliers = new CssAppliersImpl(xmlWorkerFontProvider);
var htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
PdfWriterPipeline pdfWriterPipeline = new PdfWriterPipeline(document, pdfWriter);
HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, pdfWriterPipeline);
CssResolverPipeline cssResolverPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
XMLWorker xmlWorker = new XMLWorker(cssResolverPipeline, true);
XMLParser xmlParser = new XMLParser(xmlWorker);
xmlParser.Parse(stringReader);
document.Close();
}
}
(Source: iTextSharp XmlWorker: right-to-left)
If you want an easier example, take a look at the answers of these questions:
How to parse multiple HTML files into a single PDF?
How to add a rich Textbox (HTML) to a table cell?
...
The code that parses an HTML string and a CSS string to a list of iText(Sharp) elements is as simple as this:
ElementList list = XMLWorkerHelper.parseToElementList(html, css);
You can find more examples on the official iText web site.

Categories

Resources