How can I save as word.docx in open xml - c#

I need to open a template, add some text, and then save it with a new name.
How can I save it with a new name?
String Dir = #"F:\template.docx";
WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(Dir, true);
Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
Paragraph paragraph1 = body.AppendChild(new Paragraph());
Run run1 = new Run();
RunProperties runProperties1 = new RunProperties();
Bold bold2 = new Bold();
FontSize fontSize2 = new FontSize() { Val = "28" };
runProperties1.Append(bold2);
runProperties1.Append(fontSize2);
Text text1 = new Text();
text1.Text = "text";
run1.Append(runProperties1);
run1.Append(text1);
paragraph1.Append(Hearder1);
paragraph1.Append(run1);
wordprocessingDocument.Close();

byte[] byteArray = File.ReadAllBytes("D:\Document.docx");
using (var stream = new MemoryStream())
{
stream.Write(byteArray, 0, (int)byteArray.Length);
using (var document = WordprocessingDocument.Open(stream, true))
{
//Here fill document
}
// And save file
File.WriteAllBytes("D:\NewDocument.docx", stream.ToArray());
}

Related

How to replace PDF field value by Image using iText7 in .NETCore

I've implemented it in iTextSharp but now i want to convert into iText7.
var pdfReader = new PdfReader(pdfPath1);
string outputfile = string.Empty;
var pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
var pdfFormFields = pdfStamper.AcroFields;
outputfile = string.Empty;
if (!String.IsNullOrEmpty(sign1))
{
PushbuttonField pushbuttonField = pdfFormFields.GetNewPushbuttonFromField("imgSign1");
pushbuttonField.Layout = PushbuttonField.LAYOUT_ICON_ONLY;
pushbuttonField.ProportionalIcon = true;
pushbuttonField.Image = iTextSharp.text.Image.GetInstance(sign1);
pdfFormFields.ReplacePushbuttonField("imgSign1", pushbuttonField.Field);
}
i've tried to convert it but not getting proper way
var pdfReader = new PdfReader(pdfPath1);
var fstream = new FileStream(newFile, FileMode.Create);
var pdfwriter = new PdfWriter(fstream);
var document = new PdfDocument(pdfReader, pdfwriter);
var acroForm = PdfAcroForm.GetAcroForm(document, true);
outputfile = string.Empty;
if (!string.IsNullOrEmpty(sign1))
{
//what will be the alternative for PushbuttonField in iText7.
}

iTextSharp Fill Pdf Form Image Field

I created a pdf form with Acrobat DC 2015. I have a image field on it. I fill text field succesfully. But I don't know how to fill image field. Do you help me?
private static void FillPdfForm()
{
// Original File
const string pdfTemplate = #"pdf\form.pdf";
// New file which will be created after fillin PDF
var newFile = #"pdf\FilledCV.PDF";
var pdfReader = new PdfReader(pdfTemplate);
var pdfStamper = new PdfStamper(pdfReader, new FileStream(
newFile, FileMode.Create));
var pdfFormFields = pdfStamper.AcroFields;
// So one of our fields in PDF is FullName I am filling it with my full name
pdfFormFields.SetFieldProperty("01", "textsize", 8f, null);
pdfFormFields.SetField("01", "Example");
// flatten the form to remove editting options, set it to false
// to leave the form open to subsequent manual edits
foreach (var de in pdfReader.AcroFields.Fields)
{
pdfFormFields.SetFieldProperty(de.Key.ToString(),
"setfflags",
PdfFormField.FF_READ_ONLY,
null);
}
pdfStamper.FormFlattening = false;
pdfStamper.FormFlattening = false;
pdfStamper.Close();
}
I fixed it.
private static void FillPdfForm()
{
const string pdfTemplate = #"pdf\form.pdf";
var newFile = #"pdf\FilledCV.PDF";
var pdfReader = new PdfReader(pdfTemplate);
var pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
var pdfFormFields = pdfStamper.AcroFields;
string TestImage = #"pdf\test.jpg";
PushbuttonField ad = pdfFormFields.GetNewPushbuttonFromField("08");
ad.Layout = PushbuttonField.LAYOUT_ICON_ONLY;
ad.ProportionalIcon = true;
ad.Image = Image.GetInstance(TestImage);
pdfFormFields.ReplacePushbuttonField("08", ad.Field);
pdfFormFields.SetFieldProperty("01", "textsize", 8f, null);
pdfFormFields.SetField("01", "Example");
foreach (var de in pdfReader.AcroFields.Fields)
{
pdfFormFields.SetFieldProperty(de.Key,"setfflags",PdfFormField.FF_READ_ONLY,null);
}
pdfStamper.FormFlattening = false;
pdfStamper.Close();
}

iTextSharp - How to add canvas or image to pdf from HTML string using XMLWorkerHelper?

public string GetPDF(string pHTML)
{
byte[] pdf; // result will be here
var cssText = System.IO.File.ReadAllText(HttpContext.Server.MapPath("~/Content/bootstrap.css"));
cssText=cssText + System.IO.File.ReadAllText(HttpContext.Server.MapPath("~/Content/styles.css"));
var html = pHTML;
using (var memoryStream = new MemoryStream())
{
var document = new Document(PageSize.A4, 15, 15, 15, 15);
var writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
using (var cssMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cssText)))
{
using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlMemoryStream, cssMemoryStream);
}
}
document.Close();
pdf = memoryStream.ToArray();
}
var temp = Convert.ToBase64String(pdf);
return temp;
}
I pass the html string from razor view to controller but image tag closing error shown when XMLWorkerHelper try to parse and if i direcly pass image tag string from code behind then no image shown
public string GetPDF(string pHTML)
{
byte[] pdf;
using (var memoryStream = new MemoryStream())
{
using (var doc = new Document(PageSize.A4, 15, 15, 15, 15))
{
var writer = PdfWriter.GetInstance(doc, memoryStream);
writer.PageEvent = new PDFEvents();
doc.Open();
var html = pHTML;
var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
tagProcessors.RemoveProcessor(HTML.Tag.IMG); // remove the default processor
tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor()); // use our new processor
CssFilesImpl cssFiles = new CssFilesImpl();
cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
var cssResolver = new StyleAttrCSSResolver(cssFiles);
var cssText = System.IO.File.ReadAllText(HttpContext.Server.MapPath("~/Content/bootstrap.css"));
cssText = cssText + System.IO.File.ReadAllText(HttpContext.Server.MapPath("~/Content/styles.css"));
cssResolver.AddCss(cssText, "utf-8", true);
var charset = Encoding.UTF8;
var hpc = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); // inject the tagProcessors
var htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer));
var pipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
var worker = new XMLWorker(pipeline, true);
var xmlParser = new XMLParser(true, worker, charset);
xmlParser.Parse(new StringReader(html));
}
pdf = memoryStream.ToArray();
}
var str= Convert.ToBase64String(pdf);
return str;}
And My client side code
I am passing xhtml to mvc action method
var doc = new DOMParser().parseFromString($('#content').html(), 'text/html');
var result = new XMLSerializer().serializeToString(doc);
$.ajax({
url: '#Url.Content("~/contoller/action")',
type: "POST",
dataType: "JSON",
data: { strHtml: result },
success: function (response) {
debugger;
var sampleBytes = base64ToArrayBuffer(response);
saveByteArray([sampleBytes], 'test.pdf');
}
});
function base64ToArrayBuffer(base64) {
var binaryString = window.atob(base64);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
}
var saveByteArray = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, name) {
var blob = new Blob(data, { type: "octet/stream" }),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
};
}());

Hebrew content not displayed when converting html to PDF using iTextSharp 5.5.8?

I am using the below code to convert an Html file to Pdf using iTextSharp
Document doc = new Document(iTextSharp.text.PageSize.A4, 10, 20, 5, 35);
var writer = PdfWriter.GetInstance(doc, new FileStream(savePath, FileMode.Create));
var xmlWorkerFontProvider = new XMLWorkerFontProvider();
var cssAppliers = new CssAppliersImpl(new MyFontProvider());
CssFilesImpl cssFiles = new CssFilesImpl();
StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
htmlContext.SetImageProvider(new ITextImageHandler());
IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(doc, writer)));
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser xmlParser = new XMLParser(true, worker, Encoding.Unicode);
doc.Open();
doc.NewPage();
xmlParser.Parse(new StringReader(htmlString.ToString()));
doc.Close();
For English content this is working fine. But if the content is in Hebrew then text is not displayed in the PDF.
I have checked other answers related to this on Stack-overflow but they seem to use HtmlParser which is deprecated. So I don't want to use that.
Please let me know if any thing else is required. Thanks for you time.
Edit: After reading the comments I have tried settings the fonts as well. But still no luck. Below is the updated code.
Document document = new Document();
PdfWriter writer =
PdfWriter.GetInstance(document, new FileStream(savePath, FileMode.Create));
document.Open();
var cssResolver = new StyleAttrCSSResolver();
XMLWorkerFontProvider fontProvider =
new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontProvider.Register(#"E:\fonts\NotoSansHebrew-Regular.ttf");
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
htmlContext.SetImageProvider(new ITextImageHandler());
PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
p.Parse(new StringReader(htmlString.ToString()));
document.Close();
Below is an adaptation of Bruno's code with some actual HTML. To run it you just need to download the font Noto Sans Hebrew and place it on your desktop. Without any modifications (except possibly filepaths) try running this code which works for me. (I tested this against 5.5.5 so 5.5.8 should absolutely work.)
var file = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
var fontFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "NotoSansHebrew-Regular.ttf");
var htmlText = #"<div dir=""rtl"" style=""font-family: Noto Sans Hebrew;"">שלום עולם</div>";
using (var FS = new System.IO.FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var document = new Document()) {
using (var writer = PdfWriter.GetInstance(document, FS)) {
document.Open();
var cssResolver = new StyleAttrCSSResolver();
var fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontProvider.Register(fontFile);
var cssAppliers = new CssAppliersImpl(fontProvider);
var htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
var pdf = new PdfWriterPipeline(document, writer);
var html = new HtmlPipeline(htmlContext, pdf);
var css = new CssResolverPipeline(cssResolver, html);
var worker = new XMLWorker(css, true);
var p = new XMLParser(worker);
using (var ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(htmlText))) {
using (var sr = new StreamReader(ms)) {
p.Parse(sr);
}
}
document.Close();
}
}
}
The trick to this whole thing is to get the exact name of the font in your HTML as it is in the font file. What's confusing sometimes is that fonts can actually have a bunch of names inside of them. And the older the font, the more likely that its going to have these. If I remember correctly, iText has some heuristics for determining the font name but if you want to play it safe you can also just use an alias and call it whatever you want. For instance, you can change the HTML to:
var htmlText = #"<div dir=""rtl"" style=""font-family: Gerp;"">שלום עולם</div>";
And everything will work just fine as long as you alias your font when registering it:
fontProvider.Register(fontFile, "Gerp");

How to add bootstrap.css to pdf document itextsharp

took as a basis for this
http://dangtrung87.blogspot.com/2013/07/asp-generate-pdf-with-itextsharp.html
i have next code
string htmlText = RenderViewToString(this.ControllerContext, "report", null, true);
htmlText = System.Text.RegularExpressions.Regex.Replace(htmlText, #"\s+", " ");
htmlText = htmlText.Replace("\n", "").Replace("\r","").Trim();
//Generate PDF
using (var document = new Document(PageSize.A4, 40, 40, 40, 40))
{
htmlText = FormatImageLinks(htmlText);
//define output control HTML
var memStream = new MemoryStream();
TextReader xmlString = new StringReader(htmlText);
PdfWriter writer = PdfWriter.GetInstance(document, memStream);
//open doc
document.Open();
string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
// Set factories
var htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
// Set css
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
cssResolver.AddCssFile(HttpContext.Server.MapPath("~/Content/bootstrap.css"), true);
cssResolver.AddCss(".shadow {background-color: #ebdddd; }", true);
var worker = new XMLWorker(pipeline, true);
var xmlParse = new XMLParser(true, worker);
xmlParse.Parse(xmlString);
xmlParse.Flush();
document.Close();
document.Dispose();
return File(memStream.ToArray(), "application/pdf", "test.pdf");
}
I have error here xmlParse.Parse(xmlString);
Additional information: Input string was invalid.
if i change
cssResolver.AddCssFile(HttpContext.Server.MapPath("~/Content/bootstrap.css"), false); i have no error.
And i have pdf file but work only cssResolver.AddCss(".shadow {background-color: #ebdddd; }", true);
bootstrap style is not work (
how to correct add this ??
The reason you have this error is because cssResolver must be initialized before being used in pipeline, try changing these lines
// Set css
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
cssResolver.AddCssFile(HttpContext.Server.MapPath("~/Content/bootstrap.css"), true);
cssResolver.AddCss(".shadow {background-color: #ebdddd; }", true);
by
// Set css
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile(HttpContext.Server.MapPath("~/Content/bootstrap.css"), true);
cssResolver.AddCss(".shadow {background-color: #ebdddd; }", true);
IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
Try it, works fine for me.
Regards

Categories