How to get resource names for optional content group in a pdf? - pdf

I am trying to implement functionality to allow user to add markups to existing layers in a pdf. Here is the code that I am using to draw lines on to a layer in a pdf:
PDResources resources = page.findResources();
PDPropertyList props = resources.getProperties();
COSName resourceName = getLayerResourceName("Superimposed3", resources, props);
PDPageContentStream cs1 = new PDPageContentStream(document, page, true, false);
cs1.beginMarkedContentSequence(COSName.OC, resourceName);
cs1.setStrokingColor(0, 0, 255);
cs1.setLineWidth(0.8F);
cs1.drawLine(100,100,250,200);
cs1.endMarkedContentSequence();
cs1.close();
I am using beginMarkedContentSequence instead of beginMarkedContent as I am using pdfbox 1.8 version and 2.0.5 version is not available for .net.
Here, is my function to get resource name for a layer:
private static COSName getLayerResourceName(string layerName,PDResources resources,PDPropertyList props)
{
int index = 0;
COSName resourceName = COSName.getPDFName("MC"+ index);
PDOptionalContentGroup ocg = props.getOptionalContentGroup(resourceName);
if (ocg != null && (ocg.getName() == layerName))
{
return resourceName;
}
else if (ocg == null)
{
return null;
}
else
{
resourceName = null;
index++;
bool exitFlag = false;
while (!exitFlag)
{
resourceName = COSName.getPDFName("MC" + index);
ocg = props.getOptionalContentGroup(resourceName);
if (ocg == null)
{
exitFlag = true;
resourceName = null;
}
else if (ocg.getName() == layerName)
{
exitFlag = true;
}
else
{
index++;
}
}
}
return resourceName;
}
The above functions only works for those layers which were added using the LayerUtility.appendFormAsLayer function. But it doesn't work for those layers which were created using the following code:
PDOptionalContentProperties ocprops = document.getDocumentCatalog().getOCProperties();
PDOptionalContentGroup newGroup = new PDOptionalContentGroup("Superimposed2");
PDOptionalContentGroup newGroup1 = new PDOptionalContentGroup("Superimposed3");
ocprops.addGroup(newGroup);
ocprops.addGroup(newGroup1);
So, shall I add "MC" value in properties of page myself while, creating layer, or is there another way to get resource name for such layers.

Related

Asp.Net Core - Control empty Excel cells to enter information in the database?

I use the EPPlus plugin to get information from Excel.The following code works perfectly, but how to control it when it gets an error after it reaches the empty Excel cell?
public async Task<IActionResult> AddExcellHorse(IFormFile ExcelFile)
{
using (var stream = new MemoryStream())
{
await ExcelFile.CopyToAsync(stream);
using (var package = new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
var rowCount = worksheet.Dimension.Rows;
for (int i = 2; i <= rowCount; i++)
{
AddExcelHorse viewModel = new AddExcelHorse()
{
MicrochipCode = worksheet.Cells[i, 1].Value.ToString().Trim(),
EnHorseName = worksheet.Cells[i, 2].Value.ToString().Trim(),
EnFatherHorseName = worksheet.Cells[i, 3].Value.ToString().Trim(),
EnMotherHorseName = worksheet.Cells[i, 4].Value.ToString().Trim(),
};
if (viewModel.MicrochipCode != null)
{
if (!_admin.ChechMicrochip(viewModel.MicrochipCode))
{
_admin.AddExcelHorse(viewModel);
}
} }
return RedirectToAction(nameof(Index));
}
}
}
I assume you run into a null reference exception, because the cell value is null, then .ToString() cannot be called.
You could wrap everything in a seperate if-block:
if(worksheet.Cells[i, 1].Value != null)
{
MicrochipCode = worksheet.Cells[i, 1].Value.ToString().Trim(),
}
or you use the null propagation:
MicrochipCode = worksheet.Cells[i, 1].Value?.ToString().Trim(),
//or with default value, if null is not good enough.
MicrochipCode = worksheet.Cells[i, 1].Value?.ToString().Trim() ?? String.Empty,

itext pdf verify if signature is visible or invisible

I am currently using Itext 5.4.4 and I would like to know if it is possible to check if a signature in my current PDF is visible or invisible. Is this possible? Or do I have to upgrade to a newer versiĆ³n of Itext?
You can do it like the code below. Other flags are easily added..
PdfReader reader; //instantiate
AcroFields acroFields = reader.getAcroFields();
Map<String, Item> fieldNames = acroFields.getFields();
Set<Entry<String, Item>> entries = fieldNames.entrySet();
Iterator<Entry<String, Item>> it = entries.iterator();
while(it.hasNext()){
Entry<String, Item> entry = it.next();
//Check flags
boolean invisible = isInvisible(entry.getValue());
boolean mandatory = isMandatory(entry.getValue());
boolean noView = isNoView(entry.getValue());
boolean hidden = isHidden(entry.getValue());
...
}
public static boolean isInvisible(Item item) {
//Add a nullcheck!
if(item.size()>0) {
PdfDictionary d = item.getMerged(0);
PdfNumber num = (PdfNumber) d.get(PdfName.F);
return num == null ? false : ((num.intValue() & PdfAnnotation.FLAGS_INVISIBLE) == PdfAnnotation.FLAGS_INVISIBLE);
}
return false;
}
public static boolean isMandatory(Item item) {
//Add a null check here!
if(item.size()>0) {
PdfDictionary d = item.getMerged(0);
PdfNumber num = (PdfNumber) d.get(PdfName.FF);
return num == null ? false : ((num.intValue() & PdfFormField.FF_REQUIRED) == PdfFormField.FF_REQUIRED);
}
return false;
}
public static boolean isNoView(Item item) {
//nullcheck!
if(item.size()>0) {
PdfDictionary d = item.getMerged(0);
PdfNumber num = (PdfNumber) d.get(PdfName.F);
return num == null ? false : ((num.intValue() & PdfAnnotation.FLAGS_NOVIEW) == PdfAnnotation.FLAGS_NOVIEW);
}
return false;
}
public static boolean isHidden(Item item) {
//Nullcheck!
if(item.size()>0) {
PdfDictionary d = item.getMerged(0);
PdfNumber num = (PdfNumber) d.get(PdfName.F);
return num == null ? false : ((num.intValue() & PdfAnnotation.FLAGS_HIDDEN) == PdfAnnotation.FLAGS_HIDDEN);
}
return false;
}

Make OCG layer visible when field isn't empty?

Is it possible to check when a field is not empty and if not, make an ocg layer visible?
var ocg = FindOCG("Item 1 Arrow");
if (+event.value === '') {
ocg.state = !ocg.state;
} else {
ocg.state = !ocg.state;
}
Something like this (which doesn't work)!
Put this in the custom format script of the field in question. Replace "Square" with the name of your layer. You can see an example of it working here.
function getOCGByName(cName, nPage) {
var ocg = null;
var ocgArray = this.getOCGs(nPage);
for (var i=0; i < ocgArray.length; i++) {
if (ocgArray[i].name == cName) {
ocg = ocgArray[i];
}
}
return ocg;
}
var field = event.target;
var ocg = getOCGByName("Square", this.pageNum);
if (field.value.length > 0) {
ocg.state = true;
}
else {
ocg.state = false;
}
Note: This will only work in Adobe Acrobat and Reader and a few other viewers that are JavaScript capable.

JSFL - Adding a movieclip to a specific layer and frame

I am trying to replace an outdated movieclip with a newer one.
To do this I'm usin JSFL to locate the old movieclips, save a reference, then add the new version in its place.
I have looked at addItem addItemToDocument and they successfully add the clip, but I'm unsure of how to add it to the specific layer and frame that the old instance of the movieclip was on.
Halps
Replacing all instances of the old movieclip with instances of the new movieclip, could be an easier solution.
All instances of the old movieclip can be found by parsing the timelines of the flash document.
Here is some code:
var _doc = (fl.getDocumentDOM() ? fl.getDocumentDOM() : fl.createDocument());
var _lib = _doc.library;
fl.outputPanel.clear();
ReplaceItemWithItem('Game Layouts/card holder', 'Game Layouts/card holder new');
function ReplaceItemWithItem(oldmcname, newmcname)
{
var item1 = GetItem(oldmcname);
var item2 = GetItem(newmcname);
if (!item1) return false;
if (!item2) return false;
if (oldmcname == newmcname)
return true;
return ReplaceAllItems(item1, item2);
}
function ReplaceAllItems(item1, item2)
{
var timelines = _doc.timelines;
var i, l = timelines.length;
var items = _lib.items;
var changed = false;
// Main timelines
for (i = 0; i < l; i++)
{
var timeline = timelines[i];
changed |= ReplaceItems(timeline, item1, item2);
}
// Timelines in library items
for (i = 0, l = items.length; i < l; i++)
{
var item = items[i];
switch (item.itemType)
{
case "movie clip":
case "graphic":
case "button":
changed |= ReplaceItems(item.timeline, item1, item2);
break;
}
}
return changed;
}
function ReplaceItems(timeline, item1, item2)
{
var changed = false;
if (timeline && item1 && item2)
{
var layers = timeline.layers;
var lay, layl = layers.length;
for (lay = 0; lay < layl; lay++)
{
var layer = layers[lay];
var frames = layer.frames;
var fr, frl = frames.length;
for (fr = 0; fr < frl; fr++)
{
var frame = frames[fr];
if (frame && frame.startFrame == fr)
{
var elements = frame.elements;
var e, el = elements.length;
for (e = 0; e < el; e++)
{
var elem = elements[e];
if (elem && elem.elementType == "instance") // Elements can be empty
{
var item = elem.libraryItem;
if (item.name == item1.name)
{
elem.libraryItem = item2;
changed = true;
}
}
}
}
}
}
}
return changed;
}
function GetItem(itemname)
{
if (!_lib.selectItem(itemname))
{
alert("'" + name + "' does not exist in the library!");
return null;
}
return _lib.getSelectedItems()[0];
}
Hope this helps!

Getting all the Term Stores in Sharepoint 2010 (web services or client-side object model)?

Is it possible with Sharepoint 2010 (not 2013!) to get a list of all the Term Stores on the site using either the web services or the client-side object model?
I know 2013 has added a library for it, but that will not help me on 2010.
If not the whole list, how do I get the Term Store ID, if I know a Term (that might or might not be in the TaxonomyHiddenList)?
Someone mentioned checking out the TaxonomyFieldType fields, so I hacked together these 2 methods. I do not know if these will work under all circumstances.
First function just returns the Term Store ID which is stored in the info of the first TaxonomyFieldType* we come over.
public static string GetDefaultTermStore(string site) {
var context = new ClientContext(site);
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
return node.Value;
}
}
}
throw new Exception("Term Store ID not found!");
}
The second function goes through all the fields and gets all the possible Term Store IDs and returns them in a list.
public static List<string> GetTermStores(string site) {
var context = new ClientContext(site);
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
var hashlist = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
if (!hashlist.Contains(node.Value)) {
hashlist.Add(node.Value);
}
}
}
}
if (hashlist.Count == 0) throw new Exception("No Term Store IDs not found!");
return hashlist.ToList();
}
Is this a correct answer to my question do anyone have a more sure way to get the IDs?
Does not seem like anyone else has a good answer for this question.
I have added the utility class I made from this below. Big block of uncommented code below for those who might need:
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Services.Protocols;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Xml.XPath;
namespace VitaminTilKanbanPusher.Sharepoint {
public class SharepointTaxonomyAgent {
//URLS:
//http://www.novolocus.com/2012/02/06/working-with-the-taxonomyclientservice-part-1-what-fields-are-there/
//
public static void Test() {
var site = ConfigurationManager.AppSettings["VitaminSite"];
//var list = ConfigurationManager.AppSettings["VitaminList"];
//var id = GetDefaultTermStore(site);
//var ids = GetTermStores(site);
var rs = GetAllTermSetNames(site);
var ts = GetTermSetTerms(site, "Some Name");
//var ts = GetTermSetTerms(site, "Some other name");
//var term = GetTermInfo(site, "Priority");
//var term2 = GetTermInfo(site, "My term");
//var termset = GetTermSetInfo(site, "My term");
//var termsets = GetTermSets(site, "My term");
}
public static string GetDefaultTermStore(string site) {
var context = new ClientContext(site);
context.ExecutingWebRequest += ctx_MixedAuthRequest;
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.InternalName, f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
foreach (var field in fields) {
//field.InternalName== "TaxKeyword" -> possibly default?
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
return node.Value;
}
}
}
throw new Exception("Term Store ID not found!");
}
public static List<string> GetTermStores(string site) {
var context = new ClientContext(site);
context.ExecutingWebRequest += ctx_MixedAuthRequest;
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
var hashlist = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
if (!hashlist.Contains(node.Value)) {
hashlist.Add(node.Value);
}
}
}
}
if (hashlist.Count == 0) throw new Exception("No Term Store IDs not found!");
return hashlist.ToList();
}
private static List<TermSet> _termSets;
public static List<TermSet> GetAllTermSetNames(string site, string onlySpecificTermSetName = null) {
if (_termSets != null) {
if (onlySpecificTermSetName == null) return _termSets;
foreach (var ts in _termSets) {
if (ts.Name.Equals(onlySpecificTermSetName, StringComparison.InvariantCultureIgnoreCase)) {
return new List<TermSet>() { ts };
}
}
return new List<TermSet>();
}
var context = new ClientContext(site);
context.ExecutingWebRequest += ctx_MixedAuthRequest;
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
var hashlist = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
var termSets = new List<TermSet>();
TermSet theChosenTermSet = null;
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var ts = new TermSet();
var doc = XDocument.Parse(field.SchemaXml);
var fn = doc.Element("Field");
if (fn == null) continue;
if (fn.Attribute("DisplayName") == null) continue;
if (fn.Attribute("ID") == null) continue;
ts.Name = fn.Attribute("DisplayName").Value;
//Only 1 set?
if (onlySpecificTermSetName != null) {
if (!ts.Name.Equals(onlySpecificTermSetName, StringComparison.InvariantCultureIgnoreCase)) {
theChosenTermSet = ts;
}
}
if (fn.Attribute("Description") != null) {
ts.Description = fn.Attribute("Description").Value;
}
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
ts.TermStoreId = node.Value;
}
var node2 = doc.XPathSelectElement("//Name[text()='TermSetId']/../Value");
if (node2 != null && !string.IsNullOrEmpty(node2.Value)) {
ts.Id = node2.Value;
}
else {
continue; //No ID found
}
//Unique hites
if (!hashlist.Contains(ts.Id)) {
hashlist.Add(ts.Id);
termSets.Add(ts);
}
}
}
_termSets = termSets;
if (onlySpecificTermSetName != null) return (theChosenTermSet == null ? new List<TermSet>() : new List<TermSet>() { theChosenTermSet });
return termSets;
}
public static TermSet GetTermSetTerms(string site, string termName) {
var ts = GetAllTermSetNames(site, termName);
if (ts.Count == 0) throw new Exception("Could not find termset: " + termName);
var theTermSet = ts[0];
var proxy = new SharepointTaxWS.Taxonomywebservice();
proxy.UseDefaultCredentials = true;
proxy.PreAuthenticate = true;
proxy.Url = Path.Combine(site, "_vti_bin/taxonomyclientservice.asmx");
GetAuthCookie(proxy, site);
var lciden = 1033; //var lcidno = 1044; // System.Globalization.CultureInfo.CurrentCulture.LCID
var clientTime = DateTime.Now.AddYears(-2).ToUniversalTime().Ticks.ToString();
var termStoreId = new Guid(theTermSet.TermStoreId);// Guid.Parse(theTermSet.TermStoreId);
var termSetId = new Guid(theTermSet.Id);
string clientTimestamps = string.Format("<timeStamp>{0}</timeStamp>", clientTime);
string clientVersion = "<version>1</version>";
string termStoreIds = string.Format("<termStoreId>{0}</termStoreId>", termStoreId.ToString("D"));
string termSetIds = string.Format("<termSetId>{0}</termSetId>", termSetId.ToString("D"));
string serverTermSetTimestampXml;
string result = proxy.GetTermSets(termStoreIds, termSetIds, 1033, clientTimestamps, clientVersion, out serverTermSetTimestampXml);
var term = ParseTermSetInfo(result);
term.Description = theTermSet.Description;
term.Id = theTermSet.Id;
term.Name = theTermSet.Name;
return term;
}
//public static Term GetTermSetInfo(string site, string termName) {
// var proxy = new SharepointTaxWS.Taxonomywebservice();
// proxy.UseDefaultCredentials = true;
// proxy.PreAuthenticate = true;
// proxy.Url = Path.Combine(site, "_vti_bin/taxonomyclientservice.asmx");
// GetAuthCookie(proxy, site);
// var lciden = 1033; //var lcidno = 1044; // System.Globalization.CultureInfo.CurrentCulture.LCID
// var sets = proxy.GetChildTermsInTermSet(Guid.Parse(""), lciden, Guid.Parse("termsetguid"));
// var term = ParseTermInfo(sets);
// return term;
//}
public static Term GetTermInfo(string site, string termName) {
var proxy = new SharepointTaxWS.Taxonomywebservice();
proxy.UseDefaultCredentials = true;
proxy.PreAuthenticate = true;
proxy.Url = Path.Combine(site, "_vti_bin/taxonomyclientservice.asmx");
GetAuthCookie(proxy, site);
var lciden = 1033; //var lcidno = 1044; // System.Globalization.CultureInfo.CurrentCulture.LCID
var sets = proxy.GetTermsByLabel(termName, lciden, SharepointTaxWS.StringMatchOption.StartsWith, 100, null, false);
var term = ParseTermInfo(sets);
return term;
}
private static TermSet ParseTermSetInfo(string xml) {
//Not done
var info = XDocument.Parse(xml);
var ts = new TermSet();
ts.Terms = new List<Term>();
var n1 = info.XPathSelectElements("//T");
if (n1 != null) {
foreach (var item in n1) {
var t = new Term();
t.Id = item.Attribute("a9").Value;
t.Name = item.XPathSelectElement("LS/TL").Attribute("a32").Value;
t.TermSet = ts;
ts.Terms.Add(t);
}
}
return ts;
}
private static Term ParseTermInfo(string xml) {
var info = XDocument.Parse(xml);
var t = new Term();
var ts = new TermSet();
var n1 = info.XPathSelectElement("TermStore/T");
var n2 = info.XPathSelectElement("TermStore/T/LS/TL");
var n3 = info.XPathSelectElement("TermStore/T/TMS/TM");
if (n1 != null && n1.Attribute("a9") != null) {
t.Id = n1.Attribute("a9").Value;
}
if (n2 != null && n2.Attribute("a32") != null) {
t.Name = n2.Attribute("a32").Value;
}
if (n3 != null && n3.Attribute("a24") != null) {
ts.Id = n3.Attribute("a24").Value;
}
if (n3 != null && n3.Attribute("a12") != null) {
ts.Name = n3.Attribute("a12").Value;
}
t.TermSet = ts;
return t;
}
private static CookieCollection _theAuth;
private static bool _bNoClaims;
static void GetAuthCookie(SoapHttpClientProtocol proxy, string site) {
return;
//if (_bNoClaims) {
// return; //Ingen claims.
//}
//// get the cookie collection - authentication workaround
//CookieCollection cook = null;
//try {
// if (_theAuth == null) {
// cook = ClaimClientContext.GetAuthenticatedCookies(site, 925, 525);
// }
// else {
// cook = _theAuth;
// }
// _theAuth = cook;
// _bNoClaims = false;
//}
//catch (ApplicationException ex) {
// if (ex.Message.Contains("claim")) _bNoClaims = true;
// Console.Write("Auth feilet: " + ex.Message + " - ");
// //IGNORE
//}
//if (_theAuth != null) {
// proxy.CookieContainer = new CookieContainer();
// proxy.CookieContainer.Add(_theAuth);
//}
}
static void ctx_MixedAuthRequest(object sender, WebRequestEventArgs e) {
//add the header that tells SharePoint to use Windows Auth
e.WebRequestExecutor.RequestHeaders.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
}
}
public class TermSet {
public string Id { get; set; }
public string Name { get; set; }
public List<Term> Terms { get; set; }
public string TermStoreId { get; set; }
public string Description { get; set; }
public override string ToString() {
int tc = 0;
if (Terms != null) tc = Terms.Count;
return Name + "|" + Id + " (" + tc + "terms)";
}
}
public class Term {
public string Id { get; set; }
public string Name { get; set; }
public TermSet TermSet { get; set; }
public override string ToString() {
return Name + "|" + Id;
}
}
}