Creating a OOXML document with Track Changes enabled - openxml

How do I create a .docx with track changes enabled? I was told inside word/settings.xml I should modify w:proofState but all info in online docs of OOXML I find about that property is related to grammar and spell checking, but nothing about enabling tracking changes.

It is in word/settings.xml but the element you are looking for is w:trackRevisions.
To do this in C# using the OpenXML SDK you can use the TrackRevisions class. The following code will create a document with one paragraph and with change tracking turned on:
using (WordprocessingDocument package = WordprocessingDocument.Create(filename, WordprocessingDocumentType.Document))
{
// Add a new main document part.
package.AddMainDocumentPart();
//create a body and a paragraph
Body body = new Body();
Paragraph paragraph = new Paragraph();
paragraph.AppendChild(new Run(new Text("This document should have change tracking switched on")));
body.AppendChild(paragraph);
package.MainDocumentPart.Document = new Document(body);
//change tracking code
DocumentSettingsPart documentSettingsPart = package.MainDocumentPart.AddNewPart<DocumentSettingsPart>();
Settings settings = new Settings();
TrackRevisions trackRevisions = new TrackRevisions();
settings.Append(trackRevisions);
documentSettingsPart.Settings = settings;
// Save changes to the main document part.
package.MainDocumentPart.Document.Save();
}

Related

iText -Duplicate Fields Appear on last page

I am adding fields to an existing PDF using iText 7.NET. (7.1.16) When they are added, I wind up with a duplicate of every field on the last page. For example, in a two page document, with the below code, a second field with the same name, Field1 and red border will appear on page two, in the same position. New to iText7, guidance appreciated, Thank You
PdfReader reader = new PdfReader(inputFile);
PdfDocument pdf2 = new PdfDocument(reader, new PdfWriter(outputFile));
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf2, true);
PdfFormField tf = PdfTextFormField.CreateText(
pdf2, new Rectangle(1, 20, 30, 40), "Field1", "");
tf.SetPage(1);
tf.SetBorderColor(ColorConstants.RED);
tf.SetBorderWidth(2);
form.AddField(tf);
pdf2.Close();
So the help for the non-overloaded version of AddField(), without passing a PdfPage parameter mentions that it adds it to the last page of the document. I suppose the SetPage() on the field just results on it also being on the specified page.

Embedding font using itext 5 for PDF/UA compliance

We are currently building a proof of concept to generate PDF/UA compliant PDF from from a CSS and html (xhtml) file using xslt. We are able tag the PDF and add the appropriate metadata information.
The last major issue we are unable to solve is embedding a standard PDF font zapfdinbats, which our accessibility assessment tool complains about - using PAC 2.0 along with adobe DC built in checker.
As you can see from the image below the other fonts we are using seems automatically get embedded using the xmlworker from our CSS.
I have also tried finding the font as indicated and found one, however, it doesn't seem to be the correct one.
Here is a sample of our code
private static ReturnValue CreateFromHtml(string html)
{
ReturnValue Result = new ReturnValue();
var stream = new MemoryStream();
using (var doc = new Document(PageSize.LETTER))
{
using (var ms = new MemoryStream())
{
using (var writer = PdfWriter.GetInstance(doc, ms))
{
writer.CloseStream = false;
writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
//TAGGED PDFVERSION_1_7
//Make document tagged
writer.SetTagged();
//===============
//PDF/UA
//Set document metadata
writer.ViewerPreferences = PdfWriter.DisplayDocTitle;
doc.AddLanguage("en-US");
doc.AddTitle("document title");
writer.CreateXmpMetadata();
doc.Open();
var embedfont = HttpContext.Current.Server.MapPath("~/scripts/ZapfDingbats.ttf");
var fontProv = new XMLWorkerFontProvider();
fontProv.DefaultEncoding = "UTF-8";
fontProv.Register(embedfont);
//Testing zapfDingbats font
Font font = FontFactory.GetFont(embedfont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Paragraph p1 = new Paragraph("Testing of Fonts", font);
doc.Add(p1);
//end font processing
var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
tagProcessors.RemoveProcessor(HTML.Tag.IMG);
tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor());
var cssFiles = new CssFilesImpl();
cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
var cssResolver = new StyleAttrCSSResolver(cssFiles);
var charset = Encoding.UTF8;
var context = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
context.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors);
var htmlPipeline = new HtmlPipeline(context, new PdfWriterPipeline(doc, writer));
var cssPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
var worker = new XMLWorker(cssPipeline, true);
var xmlParser = new XMLParser(true, worker, charset);
using (var sr = new StringReader(html))
{
xmlParser.Parse(sr);
doc.Close();
ms.Position = 0;
ms.CopyTo(stream);
stream.Position = 0;
}
}
}
}
// get bytes from stream
Result.Data = stream.ToArray();
// success
Result.Success = true;
return Result;
}
Maybe there is something in the CSS we need to do (our CSS is quite large f
iText only ships with the Adobe Font Metrics (AFM) file of Zapfdingbats. This means that you can't embed that font unless you provide the corresponding PostScript Font Binary (PFB) file. This PFB file can't be shipped with iText because iText doesn't have a license to do so.
The first step to solve this, is to:
purchase a Zapfdingbats license so that you get the PFB (If I recall correctly, it's a font owned by Adobe), or
use an alternative font when you want to insert special characters (check boxes, phone symbols,...) into your text (e.g. purchase a license for the AdobePiStd font that was used as a substitution font and use that font instead of Zapfdingbats).
In your case, you provided a font ZapfDingbats.ttf which you register with the XMLWorkerFontProvider. When you register this font, it can be recognized through an alias. If ZapfDingbats.ttf isn't picked up by XML Worker, there is probably a mismatch between the name of the font used in the PDF and the alias that was used when ZapfDingbats.ttf was registered.
What is the font name used for ZapfDingbats in the CSS? You should register ZapfDingbats using that name as alias.

ITextSharp errror "Off is not a valid name for a checkbox appearance (should be Off or Yes)"

Running the following code snippet under VS 2010 using iTextSharp 5.5.6:
PdfReader reader = new PdfReader("Test.pdf");
FileStream fs = new FileStream("New.pdf", FileMode.Create);
PdfStamper p = new PdfStamper(reader, fs);
AcroFields form = p.AcroFields;
...
RadioCheckField newField = new RadioCheckField(p.Writer, new iTextSharp.text.Rectangle(20, 20), "MyCheckBox", "Off");
PdfFormField RadioField = newField.CheckField;
p.AddAnnotation(RadioField, 1);
I receive the error "ITextSharp errror "Off is not a valid name for a checkbox appearance (should be Off or Yes)" at the line declaring the RadioField object. Is this a bug? How do I work around it?
A check box can have two values:
one you define yourself in your method. That will be the value of the check box when selected.
one that is defined in ISO-32000-1: Off. That's the value of the check box when it's not selected.
There is a bug in your code because you are trying to create a check box of which the value is always Off whether it's selected or not.
Choose another value. Off is reserved for the off state. You need yo define a value for the on state. ISO-32000-1 recommends Yes.
This is how you make sure the check box is selected:
newField.Checked = true;
Unchecked is done like this:
newField.Checked = false;

Change page numbers in EvoPDF

Within a pdf it is possible to change page numbering, so the first page would be page 5, etc.
(This has nothing to do with headers and footers, i'm speaking strictly about the page numbers as they appear in the pdf toolbar)
Is it possible to control those numbers with EvoPDF?
Yes, apparently with EVOPDF v5 you can set the number to be displayed on the page using the PageNumberingStartIndex property of the PdfHeaderOptions object (same for Footers). I don't know of any examples using this.
It is not possible to change the page numbering displayed by Adobe Reader using an option in the generated PDF document. What you can do is to make the PDF viewer go to a certain page in PDF document when the document is opened. You can check the Go To a Location in a PDF Page When the Document is Opened Demo . The C# code to implement this feature is:
protected void convertToPdfButton_Click(object sender, EventArgs e)
{
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set license key received after purchase to use the converter in licensed mode
// Leave it not set to use the converter in demo mode
htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";
Document pdfDocument = null;
try
{
// Convert a HTML page to a PDF document object
pdfDocument = htmlToPdfConverter.ConvertUrlToPdfDocumentObject(urlTextBox.Text);
int goToPageNumber = int.Parse(pageNumberTextBox.Text);
if (goToPageNumber > pdfDocument.Pages.Count)
{
return;
}
// Get destination PDF page
PdfPage goToPage = pdfDocument.Pages[goToPageNumber - 1];
// Get the destination point in PDF page
float goToX = float.Parse(xLocationTextBox.Text);
float goToY = float.Parse(yLocationTextBox.Text);
PointF goToLocation = new PointF(goToX, goToY);
// Get the destination view mode
DestinationViewMode viewMode = SelectedViewMode();
// Create the destination in PDF document
ExplicitDestination goToDestination = new ExplicitDestination(goToPage, goToLocation, viewMode);
// Set the zoom level when the destination is displayed
if (viewMode == DestinationViewMode.XYZ)
goToDestination.ZoomPercentage = int.Parse(zoomLevelTextBox.Text);
// Set the document Go To open action
pdfDocument.OpenAction.Action = new PdfActionGoTo(goToDestination);
// 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=Go_To_Page_Open_Action.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
if (pdfDocument != null)
pdfDocument.Close();
}
}

Why do my PDF fields stay blank in Adobe Reader if I do not flatten the PDF document?

I use iTextSharp to populate fields in a PDF. I would like the PDF to stay editable when the user opens it (i.e. so I can't flatten the PDF).
The problem is that when I stamp the PDF and view the values in Adobe Reader the fields remain blank.
If I stamp the PDF, and flatten it, and then view the values then the fields do in fact have values.
How can I populate fields and keep the PDF editable?
Here's my method as an ASP.NET MVC action:
public ActionResult GetPdfTWOWithSurname()
{
PdfHelpers _pdfHelper = new PdfHelpers(Server, Url, "~/Content/newForm.pdf");
var outStream = new MemoryStream();
var pdfReader = new PdfReader(_pdfHelper.GetPdfBytes());
var pdfStamper = new PdfStamper(pdfReader, outStream, '\0', true); //The 'true' value is important. Otherwise the document loses some dynamic features.
pdfStamper.Writer.CloseStream = false;
pdfStamper.FormFlattening = false; //Allow editing after close.
var fields = pdfStamper.AcroFields;
//Fill in text fields...
fields.SetField("topmostSubform[0].Page2[0].InvestorDetails_Surname[0]", "This is a surname");
pdfStamper.Close();
//Get outStream bytes and return...
outStream.Seek(0, SeekOrigin.Begin);
byte[] outBytes = new byte[outStream.Length];
outStream.Read(outBytes, 0, (int)outStream.Length);
return File(outBytes, "application/pdf", "ThePdfFileTWO.pdf");
}
Note that this PDF is reader enabled, and I assume it stays that way even after the save since Adobe reader shows the "Extended" toolbox when I open the file. And the fields remain editable.
Also note that the PDF remains editable, and the fields have values... in FoxitPDF reader.
Please HELP
I have that same issue and it only happens if the PDF was created with Adobe Acrobat with Extended Features. Only option I've found is to re-create the form so that pop-up box has no reason to pop-up. GL
http://what-when-how.com/itext-5/preserving-the-usage-rights-of-reader-enabled-forms-itext-5/
set FormFalttering to False and set RemoveUsageRights() (depends from the iText version)