is there a published answer in this (Geotools MapStyle turtorial, select features) - feature-selection

Is there a published solution on Geotools userguide task?
In the link:
https://docs.geotools.org/stable/userguide/tutorial/map/style.html
there is a "Things to try":
In the Geometry and CRS tutorial we saw how to change the Coordinate Reference System of a MapContent. Try the following:
Modify this application so that you can change the CRS in which the
features are displayed.
Display the bc_voting_areas shapefile and change the CRS to
EPSG:4326
Now try to use the selection tool. You will find that it no longer
works !
I would like to find objects from different layers, who has different CRS, regardless of the map-window's CRS
This is my code that misses features in some layers (I can't understund why):
void selectFeatures(MapMouseEvent ev) {
Point screenPos = ev.getPoint();
Rectangle screenRect = new Rectangle(screenPos.x - 2, screenPos.y - 2, 5, 5);
AffineTransform screenToWorld = mapFrame.getMapPane().getScreenToWorldTransform();
Rectangle2D worldRect = screenToWorld.createTransformedShape(screenRect).getBounds2D();
ReferencedEnvelope bbox = new ReferencedEnvelope(worldRect,mapFrame.getMapContent().getCoordinateReferenceSystem());
try {
Iterator<Layer> it = map.layers().iterator();
IDs = new HashSet<>();
while (it.hasNext()) {
Layer l = it.next();
if (l.isSelected()) {
selectedFeatures = grabFeaturesInBoundingBox(bbox, l.getFeatureSource());
SimpleFeatureIterator iter = selectedFeatures.features();
while (iter.hasNext()) {
SimpleFeature feature = iter.next();
IDs.add(feature.getIdentifier());
System.out.println(" " + feature.getIdentifier());
}
iter.close();
}
}
if (IDs.isEmpty()) {
System.out.println(" no feature selected");
} else {
doSometing...
}
} catch (Exception ex) {
ex.printStackTrace();
}}
SimpleFeatureCollection grabFeaturesInBoundingBox(ReferencedEnvelope click, FeatureSource<?, ?> fs) throws Exception {
FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
SimpleFeatureCollection sfc = null;
FeatureType schema = fs.getSchema();
String geometryPropertyName = schema.getGeometryDescriptor().getLocalName();
CoordinateReferenceSystem targetCRS = schema.getGeometryDescriptor().getCoordinateReferenceSystem();
ReferencedEnvelope bbox = click.transform(targetCRS, true);
Filter filter = ff.bbox(ff.property(geometryPropertyName), bbox);
sfc = featureSource.getFeatures(filter);
return sfc;}

Related

Scaleup and Scale Down of imported DWG file in the Eyeshot Model

I imported the DWG file into the eyeshot model. For reading file I used ReadAutodesk class. I want to apply Scaleup and Scaledown on the imported DWG file. I don’t understand how to do that. Can you please help me.
This is code I used.
private void RibbonRadioButton_Click(object sender, RoutedEventArgs e) {
OpenFileDialog openFileDialog1 = new OpenFileDialog() {
Filter = "DWG File|*.dwg|pdf file|*.pdf",
Multiselect = false,
AddExtension = true,
CheckFileExists = true,
CheckPathExists = true
};
string fileName = null;
if (fileName != null || openFileDialog1.ShowDialog().Value) {
System.Windows.Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate { }));
var rfa = new ReadAutodesk(fileName != null ? fileName : openFileDialog1.FileName);
ScaleTransform aa = new ScaleTransform(2,2.5,1,1);
rfa.DoWork();
rfa.AddToScene(model1);
Entity[] toAdd = model1.Entities.Explode();
model1.RenderTransform = aa;
model1.ZoomFit();
model1.Entities.AddRange(toAdd, NOT_MODIFIED_COLOR);
model1.SetView(viewType.Top);
// Fits the model in the viewport
model1.Invalidate();
}
}

Ruta process taking long time in Java Workspace - Uima

I tried to mark paragraph which endswith space. In Ruta workspace SpaceBeforeEnter rule ran quickly. But in Java workspace same rule taking more time to excecute. Used versions as follows,
uimaj-core version =>2.10.2, ruta-core version =>2.8.1 and ruta-core-ext version =>2.8.1 in both workspace. If I use the below in SCRIPT1, I'm not facing Time issue.
Rule
DECLARE SpaceBeforeEnter;
RETAINTYPE(BREAK,SPACE,MARKUP);
SPACE+?{-PARTOF(Footnote_Block),-PARTOF(Endnote_Block),-PARTOF(TAB),-PARTOF(SpaceBeforeEnter)} MARKUP*?{-PARTOF(Math),-PARTOF(IMG)->MARK(SpaceBeforeEnter,1)} #BREAK;
RETAINTYPE;
Code Snippet:
Initialise Engine and Run Process:
Ruta script1Ruta = callRuta(Path.Engine.SCRIPT1.ordinal());
if (script1Ruta.exception == null) {
script1Ruta.run();
if (script1Ruta.exception != null){
throw new Exception("Failed.");
}}
else {
throw new Exception("Failed.");
}
try {
Ruta script2Ruta = callRuta(script1Ruta.getCasIndex(), Path.Engine.SCRIPT2.ordinal());
script2Ruta.run();
}catch(Exception e){
logger.error(e.getMessage());
}
CallRuta():
private Ruta callRuta(int script1CasIndex, int engine) {
int[] engines = new int[1];
engines[0] = engine;
return (new Ruta(script1CasIndex, engines));
}
private Ruta callRuta(int engine) {
int[] engines = new int[1];
engines[0] = engine;
return (new Ruta(engines));
}
public Ruta(int casIndex, int[] engines) {
createEngines(engines.length);
this.engineIndex[0] = engines[0];
this.casIndex = casIndex;
if (casList.size() > casIndex) {
cas = casList.get(casIndex);
}
try {
File engineFile = Path.getEngineFiles(engineIndex[0]).get(0);
engine[0] = runScript(engineFile);
if (cas == null) { // Create new CAS for first script or if cas=null
cas = engine[0].newCAS();
artifact = readFile(Path.getXhtmlFile().getAbsolutePath());
cas.setDocumentText(artifact);
casList.add(cas);
} else {
logger.info("Existing CAS is used: " + casIndex);
}
} catch (Exception e) {
logger.error(e.getMessage());
}
}
run():
public void run() {
try {
engine[0].process(cas);
if (cas == null) {
logger.debug("OUPUT CAS is null");
} else {
logger.debug("OUTPUT CAS is NOT null");
}
NoException = true;
} catch (Exception e) {
logger.error(e.getMessage());
}}
runScript():
private AnalysisEngine runScript(File engineFile) throws Exception {
String path = new File(file.toURI()).getParentFile().getAbsolutePath();
String[] pathsArray = new String[] { path };
// override the values in the descriptor when creating the description
AnalysisEngineDescription desc = AnalysisEngineFactory.createEngineDescriptionFromPath(file.getAbsolutePath(),
RutaEngine.PARAM_SCRIPT_PATHS, pathsArray, RutaEngine.PARAM_DESCRIPTOR_PATHS, pathsArray,
RutaEngine.PARAM_RESOURCE_PATHS, pathsArray);
// in case the location of the descriptor is not known...
URL sourceUrl = desc.getSourceUrl();
path = new File(sourceUrl.toURI()).getParentFile().getAbsolutePath();
pathsArray = new String[] { path };
// set the values in the description
ConfigurationParameterSettings settings = desc.getAnalysisEngineMetaData().getConfigurationParameterSettings();
settings.setParameterValue(RutaEngine.PARAM_SCRIPT_PATHS, pathsArray);
settings.setParameterValue(RutaEngine.PARAM_DESCRIPTOR_PATHS, pathsArray);
settings.setParameterValue(RutaEngine.PARAM_RESOURCE_PATHS, pathsArray);
// override the values in the descriptor when creating the analysis
// engine
AnalysisEngine ae = AnalysisEngineFactory.createEngine(desc, RutaEngine.PARAM_SCRIPT_PATHS, pathsArray,
RutaEngine.PARAM_DESCRIPTOR_PATHS, pathsArray, RutaEngine.PARAM_RESOURCE_PATHS, pathsArray);
// set the values in the analysis engine and reconfigure it
ae.setConfigParameterValue(RutaEngine.PARAM_SCRIPT_PATHS, pathsArray);
ae.setConfigParameterValue(RutaEngine.PARAM_DESCRIPTOR_PATHS, pathsArray);
ae.setConfigParameterValue(RutaEngine.PARAM_RESOURCE_PATHS, pathsArray);
ae.reconfigure();
return ae; //returns Analysis Engine
}

How do I save Xml Changes Back to the Original Document

I need to update the Styles (styles.xml) part of an MS Word document due to a problem with a vendor's product.
So far I've been able to extract and update the xml I need. The only problem, is that I don't know how to save my changes back to the document.
The code below is working just fine. I usually output the xml to the console to make sure it's going in just fine. At the end, I know I need to perform some save operation, but the XDocument.Save( /stream/) hasn't worked.
Here's where I am so far
static void FixNormal()
{
using (WordprocessingDocument doc = WordprocessingDocument.Open(_path, true))
{
// Get the Styles part for this document.
StyleDefinitionsPart stylesPart = doc.MainDocumentPart.StyleDefinitionsPart;
// If the Styles part does not exist, add it and then add the style.
if (stylesPart == null)
{
Console.WriteLine("No Style Part");
}
else
{
XDocument stylesDoc;
using (var reader = XmlNodeReader.Create(stylesPart.GetStream(FileMode.Open, FileAccess.Read)))
{
XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
Console.WriteLine(stylesPart.Styles.OuterXml);
// Create the XDocument.
stylesDoc = XDocument.Load(reader);
var xStyle = stylesDoc.Descendants(w + "styles").Descendants(w + "style").Where(x => x.Attribute(w + "styleId").Value.Equals("Normal"));
XElement style = xStyle.Single();
var q = style.Descendants(w + "qFormat").FirstOrDefault();
if (q is null)
{
XElement qFormat = new XElement(w + "qFormat");
style.Add(qFormat);
}
var r = style.Descendants(w + "rsid").FirstOrDefault();
if (r is null)
{
XElement rsid = new XElement(w + "rsid");
XAttribute val = new XAttribute(w + "val", "003C4F1E");
rsid.Add(val);
style.Add(rsid);
}
}
//doc.Save(); --- Did not work
}
}
}
I found the answer in the SAVE THE PARTS section of this page Replace the styles parts in a word processing document (Open XML SDK)
See the end of this code for the solution. You'll also see what I've tried.
static void FixNormal()
{
using (WordprocessingDocument doc = WordprocessingDocument.Open(_path, true))
{
// Get the Styles part for this document.
StyleDefinitionsPart stylesPart = doc.MainDocumentPart.StyleDefinitionsPart;
// If the Styles part does not exist, add it and then add the style.
if (stylesPart == null)
{
Console.WriteLine("No Style Part");
}
else
{
XDocument stylesDoc;
using (var reader = XmlNodeReader.Create(stylesPart.GetStream(FileMode.Open, FileAccess.Read)))
{
XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
// Create the XDocument.
stylesDoc = XDocument.Load(reader);
var xStyle = stylesDoc.Descendants(w + "styles").Descendants(w + "style").Where(x => x.Attribute(w + "styleId").Value.Equals("Normal"));
XElement style = xStyle.Single();
var q = style.Descendants(w + "qFormat").FirstOrDefault();
if (q is null)
{
XElement qFormat = new XElement(w + "qFormat");
style.Add(qFormat);
}
var r = style.Descendants(w + "rsid").FirstOrDefault();
if (r is null)
{
XElement rsid = new XElement(w + "rsid");
XAttribute val = new XAttribute(w + "val", "003C4F1E");
rsid.Add(val);
style.Add(rsid);
}
}
//doc.Save(); --- Did not work
//stylesDoc.Save(#"C:\WinTest\HooRah.xml"); -- I only use this to verify that I've updated everything correctly
//using (XmlWriter xw = XmlWriter.Create(stylesPart.GetStream(FileMode.Create, FileAccess.Write)))
//{
// stylesDoc.Save(xw); -- DID NOT WORK EITHER
// doc.Save();
//}
// THIS WORKED
stylesDoc.Save(new StreamWriter(stylesPart.GetStream(FileMode.Create, FileAccess.Write)));
}
}
}

Query in OrientDB

I try to print a query through the java console but nothing comes out. this is my code someone could help me.
I'm new to OrientDB and I'm just learning.
The query I need is to know the shortest path between two nodes and print this query on the Java console. It does not give me any errors but nothing comes out.
public class Graph {
private static final String DB_PATH = "C:/OrientDataBase/shortest_path";
static OrientGraphNoTx DBGraph;
static OrientGraphFactory factory;
public static void main(String[] args) {
factory = new OrientGraphFactory("plocal:"+DB_PATH);
DBGraph = factory.getNoTx();
HashMap<String, Vertex> nodes = new HashMap<String, Vertex>();
for(int i = 0; i <= 1000; i++)
{
Vertex v = DBGraph.addVertex("class:V");
v.setProperty("vertexID", i+"");
nodes.put(i+"", v);
}
try(BufferedReader br = new BufferedReader(new FileReader("C:/OrientDataBase/sp1.csv"))) {
int i=0;
for(String line; (line = br.readLine()) !=null ; ) {
if(i==0){
i++;
}
else{
String[] vertices = line.split(",");
String vertex1 = vertices[0];
String vertex2 = vertices[1];
String weight= vertices[2];
vertex2 = vertex2.replaceAll(" ", "");
Vertex v1 = nodes.get(vertex1);
Vertex v2 = nodes.get(vertex2);
Edge eLives = DBGraph.addEdge(null, v1, v2, "belongs");
eLives.setProperty("weight", weight);
System.out.println(v1+","+v2+","+weight);
String query = "select expand(shortestPath) from (select shortestPath(#10:0,#10:2,BOTH))";
Iterable<OrientVertex> res = DBGraph.command(new OCommandSQL(query)).execute();
while(res.iterator().hasNext()){
OrientVertex v = res.iterator().next();
System.out.println("rid: "+v.getId().toString()+"\tn:"+v.getProperty("n"));
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
I tried your code and you have to put the ticks when you do the query so, it becomes:
String query = "select expand(shortestPath) from (select shortestPath(#10:0,#10:2,'BOTH'))";
I used this csv file.
Hope it helps.
Regards

Copying fields in iTextSharp 5.4.5.0

I was under the impression that it is now possible to copy AcroFields using PdfCopy. In the release notes for iText 5.4.4.0 this is listed as possible now. However, when I try to do so it appears all the annotations (I think I am using that term correctly, still fairly new to iText...) for the fields are stripped out. It looks like the fields are there (meaning I can see the blue boxes that indicate an editable field), but they are not editable. If I try to bring the PDF up in Acrobat I get a message saying that "there are no fields, would you like Acrobat to discover them?" and most are found and marked and fields properly (check boxes aren't, but the text fields are).
I assume there is an additional step somewhere along the lines to re-add the annotations to the PdfCopy object, but I do not see a way to get the annotations from the PdfReader. I also cannot seem to find any documentation on how to do this (since AcroFields were for so long not supported in PdfCopy most of what I find is along that vein).
Due to sensitivity I cannot provide a copy of the PDF's in question, but using an altered version of a test program used earlier you can see the issue with the following code. It should generate a table with some check boxes in the four right columns. If I use the exact same code with PdfCopyFields in the MergePdfs method instead of PdfCopy it works as expected. This code does not produce any text fields, but in my main project they are part of the original parent PDF that is used as a template.
(Sorry for the long example, it has been cherry picked from a much larger application. You will need a PDF with a field named "TableStartPosition" somewhere in it and update RunTest with the correct paths for your local machine to get this to work.)
Has the PdfCopy functionality not made it into iTextSharp yet? I am using version 5.4.5.0.
class Program
{
Stream _pdfTemplateStream;
MemoryStream _pdfResultStream;
PdfReader _pdfTemplateReader;
PdfStamper _pdfResultStamper;
static void Main(string[] args)
{
Program p = new Program();
try
{
p.RunTest();
}
catch (Exception f)
{
Console.WriteLine(f.Message);
Console.ReadLine();
}
}
internal void RunTest()
{
FileStream fs = File.OpenRead(#"C:\temp\a\RenameFieldTest\RenameFieldTest\Library\CoverPage.pdf");
_pdfTemplateStream = fs;
_pdfResultStream = new MemoryStream();
//PDFTemplateStream = new FileStream(_templatePath, FileMode.Open);
_pdfTemplateReader = new PdfReader(_pdfTemplateStream);
_pdfResultStamper = new PdfStamper(_pdfTemplateReader, _pdfResultStream);
#region setup objects
List<CustomCategory> Categories = new List<CustomCategory>();
CustomCategory c1 = new CustomCategory();
c1.CategorySizesInUse.Add(CustomCategory.AvailableSizes[1]);
c1.CategorySizesInUse.Add(CustomCategory.AvailableSizes[2]);
Categories.Add(c1);
CustomCategory c2 = new CustomCategory();
c2.CategorySizesInUse.Add(CustomCategory.AvailableSizes[0]);
c2.CategorySizesInUse.Add(CustomCategory.AvailableSizes[1]);
Categories.Add(c2);
List<CustomObject> Items = new List<CustomObject>();
CustomObject co1 = new CustomObject();
co1.Category = c1;
co1.Title = "Object 1";
Items.Add(co1);
CustomObject co2 = new CustomObject();
co2.Category = c2;
co2.Title = "Object 2";
Items.Add(co2);
#endregion
FillCoverPage(Items);
_pdfResultStamper.Close();
_pdfTemplateReader.Close();
List<MemoryStream> pdfStreams = new List<MemoryStream>();
pdfStreams.Add(new MemoryStream(_pdfResultStream.ToArray()));
MergePdfs(#"C:\temp\a\RenameFieldTest\RenameFieldTest\Library\Outfile.pdf", pdfStreams);
_pdfResultStream.Dispose();
_pdfTemplateStream.Dispose();
}
internal void FillCoverPage(List<CustomObject> Items)
{
//Before we start we need to figure out where to start adding the table
var fieldPositions = _pdfResultStamper.AcroFields.GetFieldPositions("TableStartPosition");
if (fieldPositions == null)
{ throw new Exception("Could not find the TableStartPosition field. Unable to determine point of origin for the table!"); }
_pdfResultStamper.AcroFields.RemoveField("TableStartPosition");
var fieldPosition = fieldPositions[0];
// Get the position of the field
var targetPosition = fieldPosition.position;
//First, get all the available card sizes
List<string> availableSizes = CustomCategory.AvailableSizes;
//Generate a table with the number of available card sizes + 1 for the device name
PdfPTable table = new PdfPTable(availableSizes.Count + 1);
float[] columnWidth = new float[availableSizes.Count + 1];
for (int y = 0; y < columnWidth.Length; y++)
{
if (y == 0)
{ columnWidth[y] = 320; }
else
{ columnWidth[y] = 120; }
}
table.SetTotalWidth(columnWidth);
table.WidthPercentage = 100;
PdfContentByte canvas;
List<PdfFormField> checkboxes = new List<PdfFormField>();
//Build the header row
table.Rows.Add(new PdfPRow(this.GetTableHeaderRow(availableSizes)));
//Insert the global check boxes
PdfPCell[] globalRow = new PdfPCell[availableSizes.Count + 1];
Phrase tPhrase = new Phrase("Select/Unselect All");
PdfPCell tCell = new PdfPCell();
tCell.BackgroundColor = BaseColor.LIGHT_GRAY;
tCell.AddElement(tPhrase);
globalRow[0] = tCell;
for (int x = 0; x < availableSizes.Count; x++)
{
tCell = new PdfPCell();
tCell.BackgroundColor = BaseColor.LIGHT_GRAY;
PdfFormField f = PdfFormField.CreateCheckBox(_pdfResultStamper.Writer);
string fieldName = string.Format("InkSaver.Global.chk{0}", availableSizes[x].Replace(".", ""));
//f.FieldName = fieldName;
string js = string.Format("hideAll(event.target, '{0}');", availableSizes[x].Replace(".", ""));
f.Action = PdfAction.JavaScript(js, _pdfResultStamper.Writer);
tCell.CellEvent = new ChildFieldEvent(_pdfResultStamper.Writer, f, fieldName);
globalRow[x + 1] = tCell;
checkboxes.Add(f);
}
table.Rows.Add(new PdfPRow(globalRow));
int status = 0;
int pageNum = 1;
for (int itemIndex = 0; itemIndex < Items.Count; itemIndex++)
{
tCell = new PdfPCell();
Phrase p = new Phrase(Items[itemIndex].Title);
tCell.AddElement(p);
tCell.HorizontalAlignment = Element.ALIGN_LEFT;
PdfPCell[] cells = new PdfPCell[availableSizes.Count + 1];
cells[0] = tCell;
for (int availCardSizeIndex = 0; availCardSizeIndex < availableSizes.Count; availCardSizeIndex++)
{
if (Items[itemIndex].Category.CategorySizesInUse.Contains(availableSizes[availCardSizeIndex]))
{
string str = availableSizes[availCardSizeIndex];
tCell = new PdfPCell();
tCell.PaddingLeft = 10f;
tCell.PaddingRight = 10f;
cells[availCardSizeIndex + 1] = tCell;
cells[availCardSizeIndex].HorizontalAlignment = Element.ALIGN_CENTER;
PdfFormField f = PdfFormField.CreateCheckBox(_pdfResultStamper.Writer);
string fieldName = string.Format("InkSaver.chk{0}.{1}", availableSizes[availCardSizeIndex].Replace(".", ""), itemIndex + 1);
//f.FieldName = fieldName; <-- This causes the checkbox to be double-named (i.e. InkSaver.Global.chk0.InkSaver.Global.chk0
string js = string.Format("hideCardSize(event.target, {0}, '{1}');", itemIndex + 1, availableSizes[availCardSizeIndex]);
f.Action = PdfAction.JavaScript(js, _pdfResultStamper.Writer);
tCell.CellEvent = new ChildFieldEvent(_pdfResultStamper.Writer, f, fieldName);
checkboxes.Add(f);
}
else
{
//Add a blank cell
tCell = new PdfPCell();
cells[availCardSizeIndex + 1] = tCell;
}
}
//Test if the column text will fit
table.Rows.Add(new PdfPRow(cells));
canvas = _pdfResultStamper.GetUnderContent(pageNum);
ColumnText ct2 = new ColumnText(canvas);
ct2.AddElement(new PdfPTable(table));
ct2.Alignment = Element.ALIGN_LEFT;
ct2.SetSimpleColumn(targetPosition.Left, 0, targetPosition.Right, targetPosition.Top, 0, 0);
status = ct2.Go(true);
if ((status != ColumnText.NO_MORE_TEXT) || (itemIndex == (Items.Count - 1)))
{
ColumnText ct3 = new ColumnText(canvas);
ct3.AddElement(table);
ct3.Alignment = Element.ALIGN_LEFT;
ct3.SetSimpleColumn(targetPosition.Left, 0, targetPosition.Right, targetPosition.Top, 0, 0);
ct3.Go();
foreach (PdfFormField f in checkboxes)
{
_pdfResultStamper.AddAnnotation(f, pageNum);
}
checkboxes.Clear();
if (itemIndex < (Items.Count - 1))
{
pageNum++;
_pdfResultStamper.InsertPage(pageNum, _pdfTemplateReader.GetPageSize(1));
table = new PdfPTable(availableSizes.Count + 1);
table.SetTotalWidth(columnWidth);
table.WidthPercentage = 100;
table.Rows.Add(new PdfPRow(this.GetTableHeaderRow(availableSizes)));
}
}
}
}
private PdfPCell[] GetTableHeaderRow(List<string> AvailableSizes)
{
PdfPCell[] sizeHeaders = new PdfPCell[AvailableSizes.Count + 1];
Phrase devName = new Phrase("Device Name");
PdfPCell deviceHeader = new PdfPCell(devName);
deviceHeader.HorizontalAlignment = Element.ALIGN_CENTER;
deviceHeader.BackgroundColor = BaseColor.GRAY;
sizeHeaders[0] = deviceHeader;
for (int x = 0; x < AvailableSizes.Count; x++)
{
PdfPCell hCell = new PdfPCell(new Phrase(AvailableSizes[x]));
hCell.HorizontalAlignment = Element.ALIGN_CENTER;
hCell.BackgroundColor = BaseColor.GRAY;
sizeHeaders[x + 1] = hCell;
}
return sizeHeaders;
}
public void MergePdfs(string filePath, List<MemoryStream> pdfStreams)
{
//Create output stream
FileStream outStream = new FileStream(filePath, FileMode.Create);
Document document = null;
if (pdfStreams.Count > 0)
{
try
{
int PageCounter = 0;
//Create Main reader
PdfReader reader = new PdfReader(pdfStreams[0]);
PageCounter = reader.NumberOfPages;//This is if we have multiple pages in the cover page, we need to adjust the offset.
//rename fields in the PDF. This is required because PDF's cannot have more than one field with the same name
RenameFields(reader, PageCounter++);
//Create Main Doc
document = new Document(reader.GetPageSizeWithRotation(1));
//Create main writer
PdfCopy Writer = new PdfCopy(document, outStream);
//PdfCopyFields Writer = new PdfCopyFields(outStream);
//Open document for writing
document.Open();
////Add pages
Writer.AddDocument(reader);
//For each additional pdf after first combine them into main document
foreach (var PdfStream in pdfStreams.Skip(1))
{
PdfReader reader2 = new PdfReader(PdfStream);
//rename PDF fields
RenameFields(reader2, PageCounter++);
// Add content
Writer.AddDocument(reader);
}
//Writer.AddJavaScript(PostProcessing.GetSuperscriptJavaScript());
Writer.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (document != null)
document.Close();
foreach (var Strm in pdfStreams)
{
try { if (null != Strm) Strm.Dispose(); }
catch { }
}
//pdfStamper.Close();
outStream.Close();
}
}
}
private void RenameFields(PdfReader reader, int PageNum)
{
int tempPageNum = 1;
//rename all fields
foreach (string field in reader.AcroFields.Fields.Keys)
{
if (((reader.AcroFields.GetFieldType(field) == 1) || (reader.AcroFields.GetFieldType(field) == 2)) && (field.StartsWith("InkSaver")))
{
//This is a InkSaver button, set the name so its subclassed
string classPath;
if (reader.AcroFields.GetFieldType(field) == 2)
{
classPath = field.Substring(0, field.LastIndexOf("."));
if (field.StartsWith("InkSaver.chk"))
{
int a = field.LastIndexOf(".");
string sub = field.Substring(a + 1, (field.Length - a - 1));
int pageNum = int.Parse(sub);
int realPageNum = pageNum + tempPageNum;//PostProcessing.Instance.CoverPageLength;
PageNum = realPageNum;
}
}
else
{
classPath = field.Substring(0, field.LastIndexOf("."));
}
string newID = classPath + ".page" + PageNum.ToString();
bool ret = reader.AcroFields.RenameField(field, newID);
}
else
{
reader.AcroFields.RenameField(field, field + "_" + PageNum.ToString());// field + Guid.NewGuid().ToString("N"));
}
}
}
}
public class ChildFieldEvent : IPdfPCellEvent
{
protected PdfWriter writer;
protected PdfFormField parent;
protected string checkBoxName;
internal ChildFieldEvent(PdfWriter writer, PdfFormField parent, string CheckBoxName)
{
this.writer = writer;
this.parent = parent;
this.checkBoxName = CheckBoxName;
}
public void CellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] cb)
{
createCheckboxField(rect);
}
private void createCheckboxField(Rectangle rect)
{
RadioCheckField bt = new RadioCheckField(this.writer, rect, this.checkBoxName, "Yes");
bt.CheckType = RadioCheckField.TYPE_SQUARE;
bt.Checked = true;
this.parent.AddKid(bt.CheckField);
}
}
internal class CustomCategory
{
internal static List<string> AvailableSizes
{
get
{
List<string> retVal = new List<string>();
retVal.Add("1");
retVal.Add("2");
retVal.Add("3");
retVal.Add("4");
return retVal;
}
}
internal CustomCategory()
{
CategorySizesInUse = new List<string>();
}
internal List<string> CategorySizesInUse { get; set; }
}
internal class CustomObject
{
internal string Title { get; set; }
internal CustomCategory Category { get;set; }
}
Please take a look at the MergeForms example. Your example is too long for me to read, but at first sight, I'm missing the following line:
copy.setMergeFields();
By the way, in MergeForms2, the fields are also renamed before the form is merged.