I am migrating an application from asp.net MVC to Aspnet Core v2.1.
I have the following code to generate a Word Document and when I hover over the document I can see the properties such as Paragraphs, Images, Footer etc all set; but when I save I always get a 5Kb document with no content. It should return the document as a stream to download by the browser, but I have also included an explicit .SaveAs("C:\blah") which produces same file.
var fileStream = new MemoryStream();
DocX document = DocX.Create(fileStream, DocumentTypes.Document);
Paragraph p1 = document.InsertParagraph();
p1.Append("Hello world");
document.SaveAs(fileStream);
fileStream.Position = 0;
fileStream.Seek(0, SeekOrigin.Begin);
document.SaveAs("C:\\Code\\MyFile.docx");
var fsr = new FileStreamResult(fileStream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
fsr.FileDownloadName = "MyFile.docx";
return fsr;
I don't get any errors either in the application or in my Event Viewer.
Any ideas?
Looks like the DocX library by Xceed is not yet supporting .Net Core. DocX is not supported in .net core applications.
You can try using EPPlus instead.
Related
I have tried to generate PDF from HTML template using wkhtmltopdf on .NET Core 5 web API, but it keeps returning the error
“wkhtmltopdf” cannot be opened because the developer cannot be verified.
System.Exception
at Wkhtmltopdf.NetCore.WkhtmlDriver.Convert(String wkhtmlPath, String switches, String html)
at Wkhtmltopdf.NetCore.GeneratePdf.GetPDF(String html)
I downloaded the Rotativa folder that contains .dll, I also set the properties to Always for Copy.
Here is my code
var HTML =#"<!DOCTYPE HTML> <HTML><h2></h2></HTML>"
var pdf = _generatePdf.GetPDF("html");
var pdfStream = new System.IO.MemoryStream();
return new FileStreamResult(pdfStream, "application/pdf");
Is it possible to use iText 7 to flatten an XFA PDF? I'm only seeing Java documentation about it (http://developers.itextpdf.com/content/itext-7-examples/itext-7-form-examples/flatten-xfa-using-pdfxfa).
It seems like you can use iTextSharp, however to do this.
I believe it's not an AcroForm PDF because doing something similar to this answer How to flatten pdf with Itext in c#? simply created a PDF that wouldn't open properly.
It looks like you have to use iTextSharp and not iText7. Looking at the NuGet version it looks like iTextSharp is essentially the iText5 .NET version and like Bruno mentioned in the comments above, the XFA stuff simply hasn't been ported to iText7 for .NET.
The confusion stemmed from having both iText7 and iTextSharp versions in NuGet and also the trial page didn't state that the XFA worker wasn't available for the .NET version of iText7 (yet?)
I did the following to accomplish what I needed at least for a trial:
Request trial copy here: http://demo.itextsupport.com/newslicense/
You'll be emailed an xml license key, you can just place it on your desktop for now.
Create a new console application in Visual Studio
Open the Project Manager Console and type in the following and press ENTER (this will install other dependencies as well)
Install-Package itextsharp.xfaworker
Use the following code:
static void Main(string[] args)
{
ValidateLicense();
var sourcePdfPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "<your_xfa_pdf_file>");
var destinationPdfPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "output.pdf");
FlattenPDF(sourcePdfPath, destinationPdfPath);
}
private static void ValidateLicense()
{
var licenseFileLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "itextkey.xml");
iTextSharp.license.LicenseKey.LoadLicenseFile(licenseFileLocation);
}
private static void FlattenPDF(string sourcePdfPath, string destinationPdfPath)
{
using (var sourcePdfStream = File.OpenRead(sourcePdfPath))
{
var document = new iTextSharp.text.Document();
var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(destinationPdfPath, FileMode.Create));
var xfaf = new iTextSharp.tool.xml.xtra.xfa.XFAFlattener(document, writer);
sourcePdfStream.Position = 0;
xfaf.Flatten(new iTextSharp.text.pdf.PdfReader(sourcePdfStream));
document.Close();
}
}
The trial will put a huge watermark on the resulting PDF, but at least you can get it working and see how the full license should work.
For IText 7 this could be done in the following way
LicenseKey.LoadLicenseFile(#"Path of the license file");
MemoryStream dest_File = new MemoryStream();
XFAFlattener xfaFlattener = new XFAFlattener();
xfaFlattener.Flatten(new MemoryStream( File.ReadAllBytes(#"C:\\Unflattened file")), dest_File);
File.WriteAllBytes("flatten.pdf", dest_File.ToArray());
I know several people asked questions like this, but no answer helped to solve my problem.
Well, I have xsl and xml and want to generate pdf with a processor like Apache.FOP.
I am not able to use any JAVA programms like that. Just able to use C# libraries / exe.
I tried to use nFop:
Version 1.x uses Java.io and..
Version 2.0 doesn't have the ability to set XsltSettings
My current Software uses XSL + XML -> HTML (using standard Stystm.Xml.Xsl on C#) and wktmltopdf to generate PDF from created HTML.
But tables got split when they are too long for the page, and on the next page you don't have any column headers (this is very important for my problem).
I think there are no Free FO-Processor for pure C
Have a look at FoNET.
public static bool XMLToPDF(string pXmlFile, string pXslFile, string pFoFile, string pPdfFile)
{
string lBaseDir = System.IO.Path.GetDirectoryName(pXslFile);
XslCompiledTransform lXslt = new XslCompiledTransform();
lXslt.Load(pXslFile);
lXslt.Transform(pXmlFile, pFoFile);
FileStream lFileInputStreamFo = new FileStream(pFoFile, FileMode.Open);
FileStream lFileOutputStreamPDF = new FileStream(pPdfFile, FileMode.Create);
FonetDriver lDriver = FonetDriver.Make();
lDriver.BaseDirectory = new DirectoryInfo(lBaseDir);
lDriver.CloseOnExit = true;
lDriver.Render(lFileInputStreamFo, lFileOutputStreamPDF);
lFileInputStreamFo.Close();
lFileOutputStreamPDF.Close();
return System.IO.File.Exists(pPdfFile);
}
I am working in asp.net with C# website. I want to convert a HTML DIV which contains various html elements like divs,label, tables and images with css styles(background color, cssClass etc) and I want its whole content to be converted into PDF using iTextSharp DLL but here I am facing a issue that css is not getting applied.Can any one help me by providing any example or code snippet.
Install 2 NuGet packages iTextSharp and itextsharp.xmlworker and use the following code:
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
byte[] pdf; // result will be here
var cssText = File.ReadAllText(MapPath("~/css/test.css"));
var html = File.ReadAllText(MapPath("~/css/test.html"));
using (var memoryStream = new MemoryStream())
{
var document = new Document(PageSize.A4, 50, 50, 60, 60);
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();
}
Check out Pechkin, a C# wrapper for wkhtmltopdf.
Specifically at this point in time (considering a pending pull request) I'd check out this fork that addresses a couple of bugs (particularly helpful in IIS based on my experience).
If you don't go with the fork / get other stability issues you may want to look at having some kind of "render queue" (e.g. in a database) and have a background process (e.g. Windows service) periodically run over the queue and render then store the binary content somewhere (either in database as well, or on file system). This depends entirely on your use-case though.
Alternatively the similar solution #DaveDev has comment linked to.
I need to extract formatted text snippets of a Word document and store it inside an SQL Server table, for later processing and then reinsertion in the Word document using C#.
I've had a look at the Word DOM and it seems that I need to use a combination of the Document.Load(), Document.Save() and Range.Copy(), Range.Paste() methods to create a file for each snippets that I then load into the DB.
Isn't there a easier (more efficient way)?
By the way the code snippets can be hidden text and I was thinking about storing the snippets as RTF.
Finally I got to use Aspose.Words for .NET to extract the code snippets from the Word file I'm interested in and store them as RTF:
// Get insteresting code snippets (in this case text runs with
// style "tw4winMark")
Document sourceDocument = new Document(fileName);
var runs = sourceDocument.GetChildNodes(NodeType.Run, true)
.Select(r => r.Font.StyleName == "tw4winMark").ToList();
// Store snippets into temporary document
// Read Aspose documentation for details
Document document = new Document();
if (runs.Count > 0) {
NodeImporter nodeImporter = new NodeImporter(
runs[0].Document,
document,
ImportFormatMode.KeepSourceFormatting
);
foreach (Run run in runs) {
Run importedRun = nodeImporter.ImportNode(run, true) as Run;
importedRun.Font.Hidden = false;
document.Sections[0].Body.Paragraphs[0].AppendChild(importedRun);
}
}
// save temporary document in MemoryStream as RTF
RtfSaveOptions saveOptions = new RtfSaveOptions();
MemoryStream ms = new MemoryStream();
document.Save(ms, saveOptions);
// retrieve RTF from MemoryStream
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
string rtf = sr.ReadToEnd();
One can then store the rtf into a text field of the database as usual and edit it in a RTF text control.
Document.load, then select the range via a RANGE object, then use the XML property of the range object to get the XML of that range and store it.
You can later insert the XML into another document using the reverse process.
Editing the snippets might prove interesting though, because I'm not aware of any web based WORD compatible editors.