Converting PDF with form to PDF without form - itextpdf

i have a PDF template containing a form. At present, I'm using itextpdf to fill the form fields, and save the resulting pdf.
Is there a way to get completeley rid of the pdf form (i.e. converting the pdf to a form-free pdf containing the inserted data)?

You need to set setFormFlattening to true on your PdfStamper object.
Code is from their documentation:
for (Movie movie : PojoFactory.getMovies(connection)) {
if (count == 0) {
baos = new ByteArrayOutputStream();
reader = new PdfReader(RESOURCE);
stamper = new PdfStamper(reader, baos);
stamper.setFormFlattening(true);
form = stamper.getAcroFields();
}
count++;
}
if (count > 0) {
stamper.close();
reader = new PdfReader(baos.toByteArray());
copy.addPage(copy.getImportedPage(reader, 1));
}
That way the form will be flattened when you close your PdfStamper.

Related

How to get Image Name or Id from docx file using Open xml in C#?

I am using Mvc.Net API with open XML. I need to replace multiple images in .docx file.I replace the images in current scenario but I don't get any Id or Name of the Image at my code side so facing difficulties to replace those images.
Here is my code
List<ImagePart> imgPartList = doc.MainDocumentPart.ImageParts.ToList();
foreach(ImagePart imgPart in imgPartList)
{
string Id=doc.MainDocumentPart.GetIdOfPart(imgPart);
byte[] imageBytes = File.ReadAllBytes(ImagePath);
BinaryWriter writer = new BinaryWriter(imgPart.GetStream());
writer.Write(imageBytes);
writer.Close();
}
Can I get the name of Image in ImagePart?
I would do something like this:
List<ImagePart> imgPartList = doc.MainDocumentPart.ImageParts.ToList();
foreach(ImagePart imgPart in imgPartList)
{
var imageId = document.MainDocumentPart.GetIdOfPart(imgPart.Id);
byte[] imageBytes = File.ReadAllBytes(ImagePath);
BinaryWriter writer = new BinaryWriter(imgPart.GetStream());
writer.Write(imageBytes);
writer.Close();
}
Also
This answer could help you

Create footer with page number not displayed using Document object of EvoPdf

I have a pdf file that converted from html by EvoPdf HtmlToPdfConverter. I read the file bytes by evopdf Document Class and add footer element to it. after saving the bytes - it's displaying inline webBrowser.
the footer with page number isn't displayed.
This is my code:
Document pdfDoc = new Document("myFilePath.pdf");
//create the footer element
TextElement footerText = new TextElement(0, 30, "Page &p; of &P; ",
new System.Drawing.Font( new System.Drawing.FontFamily("Arial"), 10, System.Drawing.GraphicsUnit.Point));
footerText.EmbedSysFont = true;
footerText.TextAlign = HorizontalTextAlign.Right;
pdfDoc.AddFooterTemplate(50);
pdfDoc.Footer.AddElement(footerText);
byte[] outBuffer = pdfDoc.Save();
pdfDoc.Close();
//...
If I add the footer element to the htmlToPdfConverter it displayed well.
how can I display it?
Thanks.
I have also run into the same situation. Basically, I wanted to add header and footer to existing PDFs without using htmltopdfconverter.
Here is the solution with a few tweaks to your existing code:
//Create a blank document.
Document MergeDocument = new Document();
Document pdfDoc = new Document("myFilePath.pdf");
//Merged n number of existing PDFs to newly created document.
MergedDocument.AppendDocument(pdfDoc, true, true, true);
//create the footer element
TextElement footerText = new TextElement(0, 30, "Page &p; of &P; ",
new System.Drawing.Font( new System.Drawing.FontFamily("Arial"), 10, System.Drawing.GraphicsUnit.Point));
footerText.EmbedSysFont = true;
footerText.TextAlign = HorizontalTextAlign.Right;
//Apply footer to the newly created document after all documents appended.
MergeDocument.AddFooterTemplate(50);
MergeDocument.Footer.AddElement(footerText);
byte[] outBuffer = MergeDocument.Save();
MergeDocument.Close();
In order to apply headers and footer on existing PDF documents you have to create an empty Document object, define the header and footer and then append the external PDF documents using the method Document.AppendDocument(Document doc, bool enableHeaderAndFooter, bool drawHeaderOnFirstPage, bool drawFooterOnFirstPage).
Below you can find a complete example for this. You can also find an online demo at Add Header and Footer in External PDF
public void protected void createPdfButton_Click(object sender, EventArgs e)
{
// Create a PDF document
Document pdfDocument = new Document();
// Add a PDF page to PDF document
PdfPage pdfPage = pdfDocument.AddPage();
try
{
// Add a default document header
AddHeader(pdfDocument, true);
// Add a default document footer
AddFooter(pdfDocument, true, true);
// Create a HTML to PDF element to add to document
HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(0, 0, urlTextBox.Text);
// Optionally set a delay before conversion to allow asynchonous scripts to finish
htmlToPdfElement.ConversionDelay = 2;
// Add HTML to PDF element to document
pdfPage.AddElement(htmlToPdfElement);
// Automatically close the external PDF documents after the final document is saved
pdfDocument.AutoCloseAppendedDocs = true;
// Insert an external PDF document in the beginning of the final PDF document
string pdfFileBefore = Server.MapPath("~/DemoAppFiles/Input/PDF_Files/Merge_Before_Conversion.pdf");
Document startExternalDocument = new Document(pdfFileBefore);
pdfDocument.InsertDocument(0, startExternalDocument, addHeaderFooterInInsertedPdfCheckBox.Checked,
showHeaderInFirstPageCheckBox.Checked, showFooterInFirstPageCheckBox.Checked);
// Append an external PDF document at the end of the final PDF document
string pdfFileAfter = Server.MapPath("~/DemoAppFiles/Input/PDF_Files/Merge_After_Conversion.pdf");
Document endExternalDocument = new Document(pdfFileAfter);
pdfDocument.AppendDocument(endExternalDocument, addHeaderFooterInAppendedPdfCheckBox.Checked, true, true);
// Save the PDF document in a memory buffer
byte[] outPdfBuffer = pdfDocument.Save();
// Send the PDF as response to browser
// Set response content type
Response.AddHeader("Content-Type", "application/pdf");
// Instruct the browser to open the PDF file as an attachment or inline
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Header_Footer_in_External_PDF.pdf; size={0}", outPdfBuffer.Length.ToString()));
// Write the PDF document buffer to HTTP response
Response.BinaryWrite(outPdfBuffer);
// End the HTTP response and stop the current page processing
Response.End();
}
finally
{
// Close the PDF document
pdfDocument.Close();
}
}
/// <summary>
/// Add a header to document
/// </summary>
/// <param name="pdfDocument">The PDF document object</param>
/// <param name="drawHeaderLine">A flag indicating if a line should be drawn at the bottom of the header</param>
private void AddHeader(Document pdfDocument, bool drawHeaderLine)
{
string headerHtmlUrl = Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Header_HTML.html");
// Create the document footer template
pdfDocument.AddHeaderTemplate(60);
// Create a HTML element to be added in header
HtmlToPdfElement headerHtml = new HtmlToPdfElement(headerHtmlUrl);
// Set the HTML element to fit the container height
headerHtml.FitHeight = true;
// Add HTML element to header
pdfDocument.Header.AddElement(headerHtml);
if (drawHeaderLine)
{
float headerWidth = pdfDocument.Header.Width;
float headerHeight = pdfDocument.Header.Height;
// Create a line element for the bottom of the header
LineElement headerLine = new LineElement(0, headerHeight - 1, headerWidth, headerHeight - 1);
// Set line color
headerLine.ForeColor = Color.Gray;
// Add line element to the bottom of the header
pdfDocument.Header.AddElement(headerLine);
}
}
/// <summary>
/// Add a footer to document
/// </summary>
/// <param name="pdfDocument">The PDF document object</param>
/// <param name="addPageNumbers">A flag indicating if the page numbering is present in footer</param>
/// <param name="drawFooterLine">A flag indicating if a line should be drawn at the top of the footer</param>
private void AddFooter(Document pdfDocument, bool addPageNumbers, bool drawFooterLine)
{
string footerHtmlUrl = Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Footer_HTML.html");
// Create the document footer template
pdfDocument.AddFooterTemplate(60);
// Set footer background color
RectangleElement backColorRectangle = new RectangleElement(0, 0, pdfDocument.Footer.Width, pdfDocument.Footer.Height);
backColorRectangle.BackColor = Color.WhiteSmoke;
pdfDocument.Footer.AddElement(backColorRectangle);
// Create a HTML element to be added in footer
HtmlToPdfElement footerHtml = new HtmlToPdfElement(footerHtmlUrl);
// Set the HTML element to fit the container height
footerHtml.FitHeight = true;
// Add HTML element to footer
pdfDocument.Footer.AddElement(footerHtml);
// Add page numbering
if (addPageNumbers)
{
// Create a text element with page numbering place holders &p; and & P;
TextElement footerText = new TextElement(0, 30, "Page &p; of &P; ",
new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point));
// Align the text at the right of the footer
footerText.TextAlign = HorizontalTextAlign.Right;
// Set page numbering text color
footerText.ForeColor = Color.Navy;
// Embed the text element font in PDF
footerText.EmbedSysFont = true;
// Add the text element to footer
pdfDocument.Footer.AddElement(footerText);
}
if (drawFooterLine)
{
float footerWidth = pdfDocument.Footer.Width;
// Create a line element for the top of the footer
LineElement footerLine = new LineElement(0, 0, footerWidth, 0);
// Set line color
footerLine.ForeColor = Color.Gray;
// Add line element to the bottom of the footer
pdfDocument.Footer.AddElement(footerLine);
}
}

Importing content to XNA program using code?

Is it possible that a XNA program able to import the resource (etc: image, sound) into the content of the program via code? For example, the user want to add an new image into the program, the XNA program will behave like the Window's Add File or Copy File. If possible WinForm shall avoid.
OpenFileDialog f = new OpenFileDialog();
f.Filter = "PNG files (*.png)|*.png|All files (*.*)|*.*";
f.Title = "Import Image";
DialogResult result = f.ShowDialog(); // Show the dialog.
string file = "";
if (result == DialogResult.OK) // Test result.
{
file = f.FileName;
}
else //If cancels, handle here
Application.Exit();
using (FileStream SourceStream = File.Open(file, FileMode.Open))
{
//Load the Texture here
YourTexture = Texture2D.FromStream(GraphicsDevice, SourceStream);
}
That uses a simple WinForms OpenDialog Window, but if you don't want winforms, you can make your own and use this part just to load.
using (FileStream SourceStream = File.Open(file, FileMode.Open))
{
//Load the Texture here
YourTexture = Texture2D.FromStream(GraphicsDevice, SourceStream);
}
You can save the Texture2D Back by doing
using(Stream stream = File.Create(file));
{
texture.SaveAsPng(stream, texture.Width, texture.Height);
}

Streaming Word Doc in OpenXML SDK using ASP.NET MVC 4 gets corrupt document

I am trying to do this on ASP.NET MVC 4:
MemoryStream mem = new MemoryStream();
using (WordprocessingDocument wordDoc =
WordprocessingDocument.Create(mem, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
{
// instantiate the members of the hierarchy
Document doc = new Document();
Body body = new Body();
Paragraph para = new Paragraph();
Run run = new Run();
Text text = new Text() { Text = "The OpenXML SDK rocks!" };
// put the hierarchy together
run.Append(text);
para.Append(run);
body.Append(para);
doc.Append(body);
//wordDoc.Close();
///wordDoc.Save();
}
return File(mem.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ABC.docx");
However the ABC.docx opens as corrupted and it wouldn't open even after fixing it.
Any ideas?
Linked Qs:
Streaming In Memory Word Document using OpenXML SDK w/ASP.NET results in "corrupt" document
Apparently the problem comes from missing this 2 lines:
wordDoc.AddMainDocumentPart();
wordDoc.MainDocumentPart.Document = doc;
Updated the code to below and it now works flawlessly, even without any extra flushing, etc necessary.
MemoryStream mem = new MemoryStream();
using (WordprocessingDocument wordDoc =
WordprocessingDocument.Create(mem, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
{
wordDoc.AddMainDocumentPart();
// instantiate the members of the hierarchy
Document doc = new Document();
Body body = new Body();
Paragraph para = new Paragraph();
Run run = new Run();
Text text = new Text() { Text = "The OpenXML SDK rocks!" };
// put the hierarchy together
run.Append(text);
para.Append(run);
body.Append(para);
doc.Append(body);
wordDoc.MainDocumentPart.Document = doc;
wordDoc.Close();
}
return File(mem.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ABC.docx");

Generate torrent links from server-side

I don't know a lot about torrents, at least not enough to understand how certain websites can offer both a normal download link and a torrent link to download a file uploaded by a user.
Is generating a torrent link something common and simple to achieve. Would I need a server installation?
I've made an ugly C# implementation from a Java source, and to make sure some of my encoded variables were correct, I used NBEncode from Lars Warholm.
// There are 'args' because I'm using it from command-line. (arg0 is an option not used here)
// Source file
args[1] = Directory.GetCurrentDirectory() + args[1];
// Name to give to the torrent file
args[2] = Directory.GetCurrentDirectory() + args[2];
var inFileStream = new FileStream(args[1], FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var filename = args[2];
//BEncoding with NBEencode
var transform = new BObjectTransform();
MemoryStream s = new MemoryStream();
OSS.NBEncode.Entities.BDictionary bod = new OSS.NBEncode.Entities.BDictionary();
OSS.NBEncode.Entities.BDictionary meta = new OSS.NBEncode.Entities.BDictionary();
// Preparing the first part of the file by creating BEncoded objects
string announceURL = "https://www.mysite.com/announce";
int pieceLength = 512 * 1024;
bod.Value.Add(new BByteString("name"), new OSS.NBEncode.Entities.BByteString(filename));
bod.Value.Add(new BByteString("length"), new OSS.NBEncode.Entities.BInteger(inFileStream.Length));
bod.Value.Add(new BByteString("piece length"), new OSS.NBEncode.Entities.BInteger(pieceLength));
bod.Value.Add(new BByteString("pieces"), new BByteString(""));
meta.Value.Add(new BByteString("announce"), new BByteString(announceURL));
meta.Value.Add(new BByteString("info"), bod);
byte[] pieces = hashPieces(args[1], pieceLength);
transform.EncodeObject(meta, s);
s.Close();
// Notice that we finish with a dictionary entry of "pieces" with an empty string.
byte[] trs = s.ToArray();
s.Close();
inFileStream.Close();
// I don't know how to write array of bytes using NBEncode library, so let's continue manually
// All data has been written a MemoryStreamp, except the byte array with the hash info about each parts of the file
Stream st = new FileStream(filename + ".torrent", FileMode.Create);
BinaryWriter bw = new BinaryWriter(st);
// Let's write these Bencoded variables to the torrent file:
// The -4 is there to skip the current end of the file created by NBEncode
for (int i = 0; i < trs.Length - 4; i++)
{
bw.BaseStream.WriteByte(trs[i]);
}
// We'll add the length of the pieces SHA1 hashes:
var bt = stringToBytes(pieces.Length.ToString() + ":");
// Then we'll close the Bencoded dictionary with 'ee'
var bu = stringToBytes("ee");
// Let's append this to the end of the file.
foreach (byte b in bt)
{
bw.BaseStream.WriteByte(b);
}
foreach (byte b in pieces)
{
bw.BaseStream.WriteByte(b);
}
foreach (byte b in bu)
{
bw.BaseStream.WriteByte(b);
}
bw.Close();
st.Close();
// That's it.
}
Functions used:
private static byte[] stringToBytes(String str)
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] bytes = encoding.GetBytes(str);
return bytes;
}
private static byte[] hashPieces(string file, int pieceLength)
{
SHA1 sha1 = new SHA1CryptoServiceProvider();
StreamReader inn = new StreamReader(file);
MemoryStream pieces = new MemoryStream();
byte[] bytes = new byte[pieceLength];
byte[] digest = new byte[20];
int pieceByteCount = 0, readCount = inn.BaseStream.Read(bytes, 0, pieceLength);
while (readCount != 0)
{
pieceByteCount += readCount;
digest = sha1.ComputeHash(bytes, 0, readCount);
if (pieceByteCount == pieceLength)
{
pieceByteCount = 0;
foreach (byte b in digest)
{
pieces.WriteByte(b);
}
}
readCount = inn.BaseStream.Read(bytes, 0, pieceLength - pieceByteCount);
}
inn.Close();
if (pieceByteCount > 0)
foreach (byte b in digest)
{
pieces.WriteByte(b);
}
return pieces.ToArray();
}
It depends on how you're trying to create it. If you run a website, and want to generate torrent files from uploaded files, then you'll obviously need server-side code.
Generating a torrent file involves: adding the files you want to the torrent, and adding tracker info. Some popular trackers are:
http://open.tracker.thepiratebay.org/announce
http://www.torrent-downloads.to:2710/announce
To create the .torrent file, you'll have to read the about the format of the file. A piece of Java that generates .torrent files is given at https://stackoverflow.com/a/2033298/384155

Resources