Create document with WordprocessingDocument and MemoryStream - c#

I am using the following code to create a MS word document using OpenXML WordprocessingDocument from a word template.I am using Stream and not using any physical location for new document.Using OpenXML ,Is is possible to create document without using a physical location (only with Stream) and finally save to a location?
I am not getting any error and new document is created successfully but the newly created document is corrupted and unable to open in MS word.
using (Stream stream1 = new FileStream("c:\\TestDoc.dotx", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) {
using (WordprocessingDocument document = WordprocessingDocument.Open(stream1, true)) {
document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
MainDocumentPart mainPart = document.MainDocumentPart;
DocumentSettingsPart documentSettingPart1 = mainPart.DocumentSettingsPart;
mainPart.Document.Save();
Stream mystream = mainPart.GetStream();
FileStream fileStream = File.Create("c:\\newdoc.docx", (int)mystream.Length);
byte[] bytesInStream = new byte[mystream.Length];
mystream.Read(bytesInStream, 0, bytesInStream.Length);
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
document.Close();
}
}

Related

NPOI 2.6.0-rc-3 with .net framework 4.8.1 for updating .xlsx - losses charts in excel file

I use NPOI 2.6.0-rc-3 with .net framework 4.8.1 for updating .xlsx file. Excel file includes charts with it. excel file get crashed and after saving. After recovering the same file it losses charts in excel.
Used the following code.
XSSFWorkbook wb1 = null;
using (var file = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
{
wb1 = new XSSFWorkbook(file);
file.Close();
//Updated the cell values here
using (var file2 = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
{
wb1.Write(file2);
file2.Close();
}
}
Please help regrading this matter
Try to modify the cells out of the using block (you dont need to keep the file open to modify the IWorkbook) and then save it using a diferent stream:
IWorkbook wb1 = null;
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
wb1 = new XSSFWorkbook(file);
}
//Updated the cell values here
using (FileStream fileWrite = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
wb1.Write(fileWrite);
}

How to return PDF using iText

I am trying to return a PDF with simple text, but getting the following error when downloading the document: Failed to load PDF document. Any ideas on how to resolve this is appreciated.
MemoryStream ms = new MemoryStream();
PdfWriter writer = new PdfWriter(ms);
PdfDocument pdfDocument = new PdfDocument(writer);
Document document = new Document(pdfDocument);
document.Add(new Paragraph("Hello World"));
//document.Close();
//writer.Close();
ms.Position = 0;
string pdfName = $"IP-Report-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.pdf";
return File(ms, "application/pdf", pdfName);
You have to close the writer without closing the underlying stream, which will flush its internal buffer. As is, the document isn't being written to the memory stream in its entirety. Everything but ms should be in a using, too.
You can verify this is occuring by checking the length of ms in your code vs. the code below.
When the using (PdfWriter writer =...) closes, it will close the writer, which causes it to flush its pending writes to the underlying stream ms.
MemoryStream ms = new MemoryStream();
using (PdfWriter writer = new PdfWriter(ms))
using (PdfDocument pdfDocument = new PdfDocument(writer))
using (Document document = new Document(pdfDocument))
{
/*
* Depending on iTextSharp version, you might instead use:
* writer.SetCloseStream(false);
*/
writer.CloseStream = false;
document.Add(new Paragraph("Hello World"));
}
ms.Position = 0;
string pdfName = $"IP-Report-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.pdf";
return File(ms, "application/pdf", pdfName);

Saving PDF to Local Disk C#

I am trying to save a PDF to the document folder. I have googled and came across a lot of resources but none of them worked for me. I have tried using showfiledialog which did not work. What I want is to save my PDF file to the documents folder. I need this done for a school project and this is the only part that has stumped me. So far this is my code:
private void savePDF_Click(object sender, EventArgs e)
{
FileStream fileStream = new FileStream(nameTxtB.Text + "Repair.pdf", FileMode.Create, FileAccess.Write, FileShare.None);
Document document = new Document();
PdfWriter pdfWriter = PdfWriter.GetInstance(document, fileStream);
pdfWriter.Open();
PdfContentByte cb = pdfWriter.DirectContent;
ColumnText ct = new ColumnText(cb);
document.Open();
...
You should add your content (nameTxtB.Text) to Paragraph not to FileStream
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;
static void Main(string[] args) {
// open the writer
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Repair.pdf");
FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
Document doc = new Document();
//Create a New instance of PDFWriter Class for Output File
PdfWriter.GetInstance(doc, fs);
//Open the Document
doc.Open();
//Add the content of Text File to PDF File
doc.Add(new Paragraph("Document Content"));
//Close the Document
doc.Close();
System.Diagnostics.Process.Start(fileName);
}

Copying PDF without loose form field structure with ItextSharp

I would like to get a pdf, keep somes pages, then save it to another destination without losing fieldstructure.
Here the code perfectly working for copying:
string sourceFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string sourceFile = Path.Combine(sourceFolder, "POMultiple.pdf");
string fileName = #"C:\Users\MyUser\Desktop\POMultiple.pdf";
byte[] file = System.IO.File.ReadAllBytes(fileName);
public static void removePagesFromPdf(byte[] sourceFile, String destinationFile, params int[] pagesToKeep)
{
//Used to pull individual pages from our source
PdfReader r = new PdfReader(sourceFile);
//Create our destination file
using (FileStream fs = new FileStream(destinationFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (Document doc = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
//Open the desitination for writing
doc.Open();
//Loop through each page that we want to keep
foreach (int page in pagesToKeep)
{
//Add a new blank page to destination document
doc.NewPage();
//Extract the given page from our reader and add it directly to the destination PDF
writer.DirectContent.AddTemplate(writer.GetImportedPage(r, page), 0, 0);
}
//Close our document
doc.Close();
}
}
}
But when I open "TestOutput.pdf" file in acrobat reader all my fields are empty.
Any Help ?
You need something like this:
PdfReader reader = new PdfReader(sourceFile);
reader.SelectPages(2-4,8-9);
PdfStamper stp = new PdfStamper(reader, new FileStream(destinationFile, FileMode.Create));
stp.Close();
reader.Close();

How to set copyright metadata of an existing PDF using iTextSharp for C#

How can the copyright metadata of an existing (i.e. a pdf loaded from file or memory stream) pdf file be set using iTextSharp for C#?
Thanks a lot
The native XMP structures don't have copyright implemented (or at least they don't in a way that Adobe Reader recognizes.) To do that you can reverse engineer what Adobe kicks out and write it manually:
String inputPDF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Services.pdf");
String outputPDF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Services_Out.pdf");
PdfReader reader = new PdfReader(inputPDF);
using (FileStream fs = new FileStream(outputPDF, FileMode.Create, FileAccess.Write, FileShare.Read))
{
using (PdfStamper stamper = new PdfStamper(reader, fs))
{
using (MemoryStream ms = new MemoryStream())
{
string CopyrightName = "YOUR NAME HERE";
string CopyrightUrl = "http://www.example.com/";
XmpWriter xmp = new XmpWriter(ms);
xmp.AddRdfDescription("xmlns:dc=\"http://purl.org/dc/elements/1.1/\"", String.Format("<dc:rights><rdf:Alt><rdf:li xml:lang=\"x-default\">{0}</rdf:li></rdf:Alt></dc:rights>", CopyrightName));
xmp.AddRdfDescription("xmlns:xmpRights=\"http://ns.adobe.com/xap/1.0/rights/\"", string.Format("<xmpRights:Marked>True</xmpRights:Marked><xmpRights:WebStatement>{0}</xmpRights:WebStatement>", CopyrightUrl));
xmp.Close();
stamper.XmpMetadata = ms.ToArray();
stamper.Close();
}
}
}

Categories