private void OpenButton_Click(object sender, EventArgs e) { if (((mCurrentDoc != null))) { mCurrentDoc.Close(); } string filename = OpenFile(); if ((!string.IsNullOrEmpty(filename))) { mCurrentDoc = mApprenticeServer.Open(filename); if ((mCurrentDoc.DocumentType == DocumentTypeEnum.kDrawingDocumentObject)) { mCurrentDrawingDoc = (ApprenticeServerDrawingDocument)mCurrentDoc; } IPictureDisp oPicDisp = (IPictureDisp)mCurrentDoc.Thumbnail; Image image = Microsoft.VisualBasic.Compatibility.VB6.Support.IPictureDispToImage(oPicDisp); //image.Save("c:\Temp\Thumbnail.bmp", System.Drawing.Imaging.ImageFormat.Bmp) PreviewPic.Image = image; PreviewPic.Refresh(); lbFilename.Text = "File: " + mCurrentDoc.DisplayName; ViewerButton.Enabled = true; } }
public static string GetInternalId(string fullFileName) { string internalId = null; ApprenticeServerComponent apprentice = null; try { apprentice = new ApprenticeServerComponent(); var document = apprentice.Open(fullFileName); internalId = (string)document.GetType().InvokeMember( "InternalName", System.Reflection.BindingFlags.GetProperty, null, document, null); } catch (Exception ex) { Console.WriteLine(ex); } finally { if (apprentice != null) { apprentice.Close(); } } return(internalId); }
private void OpenDocument() { if (!System.IO.File.Exists(this._filePath)) { throw new ArgumentNullException("filepath donot exists"); } if (_oserver == null) { throw new ArgumentNullException("oserver isnot initialized"); } if (_HWnd == 0) { throw new ArgumentNullException("hwnd isnot initialized"); } _odocument = _oserver.Open(this._filePath); if (_odocument.DocumentType == DocumentTypeEnum.kDrawingDocumentObject) { _odrawingDocument = (Inventor.ApprenticeServerDrawingDocument)_odocument; _oview = _odrawingDocument.Sheets[1].ClientViews.Add(this.HWnd); _ocamera = _oview.Camera; _ocamera.Fit(); _ocamera.Apply(); _ocamera.Perspective = false; } else { _oview = _odocument.ClientViews.Add(this.HWnd); _ocamera = _oview.Camera; _ocamera.Fit(); _ocamera.Apply(); _ocamera.ViewOrientationType = ViewOrientationTypeEnum.kBackViewOrientation; } }
public static DocumentInfo GetDocumentInfo(string fullFileName) { var documentInfo = new DocumentInfo(); ApprenticeServerComponent apprentice = null; try { apprentice = new ApprenticeServerComponent(); var document = apprentice.Open(fullFileName); documentInfo.InternalName = (string)document.GetType().InvokeMember( "InternalName", System.Reflection.BindingFlags.GetProperty, null, document, null); var propertySets = (PropertySets)document.GetType().InvokeMember( "PropertySets", System.Reflection.BindingFlags.GetProperty, null, document, null); if (propertySets != null) { foreach (PropertySet propertySet in propertySets) { if (propertySet.DisplayName == "User Defined Properties") { foreach (Property property in propertySet) { if (property.Name != "Class") { continue; } documentInfo.Class = property.Value; break; } break; } } } } catch (Exception ex) { Console.WriteLine(ex); } finally { if (apprentice != null) { apprentice.Close(); } } return(documentInfo); }
private void ReplaceReferencesMethod(string oldFilePath, string newFilePath) { try { // Open document with specific filepath ApprenticeServerComponent oApprentice = new ApprenticeServerComponent(); Document oDoc = (Document)oApprentice.Open(oldFilePath); // Find where file was used before renaming DocumentsEnumerator oDocsEnum = oDoc.ReferencingDocuments; // Save file with new name oDoc.SaveAs(newFilePath, false); // Look through referencing documents foreach (Document locDoc in oDocsEnum) { foreach (ReferencedFileDescriptor oRefFileDesc in locDoc.ReferencedFileDescriptors) { if (oRefFileDesc.FullFileName == oldFilePath) { // Replace the reference oRefFileDesc.PutLogicalFileNameUsingFull(newFilePath); } } } oApprentice = null; // Define file name string filename = System.IO.Path.GetFileName(oldFilePath); // Find IDW files and export PDF InventorPlugins.ExportPDF exportPDF = new InventorPlugins.ExportPDF(inventorApp, oDoc, oldFilePath, newFilePath); exportPDF = null; // Export to DXF InventorPlugins.ExportDXF exportDXF = new InventorPlugins.ExportDXF(inventorApp, oDoc, filename); exportDXF = null; // Close document oDoc.Close(true); oDoc = null; // Delete old files if (System.IO.File.Exists(oldFilePath)) { System.IO.File.Delete(oldFilePath); } } catch (Exception ex) { MessageBox.Show(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().Name, MessageBoxButton.OK); } }
private void buttonBrowse_Click(object sender, System.EventArgs e) { OpenFileDialog fdlg = new OpenFileDialog(); fdlg.Title = "C# Inventor Open File Dialog"; fdlg.InitialDirectory = @"c:\program files\autodesk\inventor 2013\samples\models\"; fdlg.Filter = "Inventor files (*.ipt; *.iam; *.idw)|*.ipt;*.iam;*.idw"; fdlg.FilterIndex = 2; fdlg.RestoreDirectory = true; if (fdlg.ShowDialog() == DialogResult.OK) { // get the file name textBoxFileName.Text = fdlg.FileName; m_odocument = m_oserver.Open(textBoxFileName.Text); // if drawing document, get the first sheet and from it the client views collection, then create a client view if (m_odocument.DocumentType == DocumentTypeEnum.kDrawingDocumentObject) { m_odrawingDocument = (Inventor.ApprenticeServerDrawingDocument)m_odocument; m_oview = m_odrawingDocument.Sheets[1].ClientViews.Add(pictureBox1.Handle.ToInt32()); m_ocamera = m_oview.Camera; m_ocamera.Perspective = false; } // if part or assembly get the client views collection from the document, then create a client view else { m_oview = m_odocument.ClientViews.Add(pictureBox1.Handle.ToInt32()); m_ocamera = m_oview.Camera; m_ocamera.ViewOrientationType = ViewOrientationTypeEnum.kIsoTopRightViewOrientation; } m_ocamera.Fit(); m_ocamera.Apply(); m_oview.Update(false); // using the control to display the file axInventorView1.FileName = fdlg.FileName; } }
void watcher_Created(object sender, FileSystemEventArgs e) { // A file got created. Let's check its iProperties string iProperties = "File path: " + e.FullPath + "\r\n"; // We might not always be able to open a document, e.g. // maybe if the writer locked it, so let's catch any errors try { ApprenticeServerComponent app = new ApprenticeServerComponent(); ApprenticeServerDocument doc = app.Open(e.FullPath); // Gather "Summary Information" properties PropertySet ps = doc.PropertySets["{F29F85E0-4FF9-1068-AB91-08002B27B3D9}"]; foreach (Property p in ps) { // e.g. the Thumbnail property cannot be converted to string // so that would throw an error we need to catch try { iProperties += p.DisplayName + ": " + p.Value.ToString() + "\r\n"; } catch { } } app.Close(); app = null; } catch (Exception ex) { iProperties += "Exception occurred: " + ex.Message + "\r\n"; } // Write it to the file using (StreamWriter sw = System.IO.File.AppendText(logFile)) { sw.Write(iProperties); } }
static void Main(string[] args) { try { var filePath = args[0]; if (!System.IO.File.Exists(filePath)) { System.Console.Write( string.Format("File ({0}) does not exist.", filePath)); return; } ApprenticeServerComponent asc = new ApprenticeServerComponent(); ApprenticeServerDocument asd = asc.Open(filePath); // "Inventor Summary Information" PropertySet ps = asd .PropertySets["{F29F85E0-4FF9-1068-AB91-08002B27B3D9}"]; foreach (Property p in ps) { System.Console.Write( string.Format("{0}={1};", p.DisplayName, p.Value) ); } asd.Close(); } catch (Exception ex) { System.Console.WriteLine(ex.Message); } }
// use ERP names instead of file names. private Boolean PDFfileUpdate(VDF.Vault.Currency.Entities.FileIteration fileIter, VDF.Vault.Currency.Connections.Connection connection, ref string logMessage, ref string errMessage) { try { // download the file System.IO.DirectoryInfo targetDir = new System.IO.DirectoryInfo(m_TargetFolder); if (!targetDir.Exists) { targetDir.Create(); } VDF.Vault.Settings.AcquireFilesSettings downloadSettings = new VDF.Vault.Settings.AcquireFilesSettings(connection) { LocalPath = new VDF.Currency.FolderPathAbsolute(targetDir.FullName), }; downloadSettings.AddFileToAcquire(fileIter, VDF.Vault.Settings.AcquireFilesSettings.AcquisitionOption.Download); VDF.Vault.Results.AcquireFilesResults results = connection.FileManager.AcquireFiles(downloadSettings); string fileName = downloadSettings.LocalPath.ToString() + @"\" + fileIter.ToString(); // ipts and iams are easier to deal with than idws if (fileName.EndsWith(".ipt") || fileName.EndsWith(".iam")) { PrintObject printOb = new PrintObject(); if (printOb.deletePDF(fileName, m_PDFPath, ref logMessage, ref errMessage)) { return(true); } else { return(false); } } else if (fileName.EndsWith(".idw")) // for idws we have to loop through each drawing sheet { try { string modelName = ""; // set up lists for storing the actual model names the sheets are referencing List <string> modelNames = new List <string>(); List <VDF.Vault.Currency.Entities.FileIteration> fIterations = new List <VDF.Vault.Currency.Entities.FileIteration>(); VDF.Vault.Currency.Properties.PropertyDefinitionDictionary propDefs = new VDF.Vault.Currency.Properties.PropertyDefinitionDictionary(); Inventor.ApprenticeServerComponent oApprentice = new ApprenticeServerComponent(); Inventor.ApprenticeServerDrawingDocument drgDoc; drgDoc = (Inventor.ApprenticeServerDrawingDocument)oApprentice.Document; oApprentice.Open(fileName); drgDoc = (Inventor.ApprenticeServerDrawingDocument)oApprentice.Document; ACW.PropDef[] filePropDefs = connection.WebServiceManager.PropertyService.GetPropertyDefinitionsByEntityClassId("FILE"); ACW.PropDef vaultNamePropDef = filePropDefs.Single(n => n.SysName == "Name"); // for each sheet in the idw, search the vault for the sheet's corresponding ipt or iam foreach (Sheet sh in drgDoc.Sheets) { if (sh.DrawingViews.Count > 0) // I added this line because one pdf with a BOM only sheet // kept failing. This line fixed the problemf or that file // but it is definitely not well tested... { errMessage += " " + sh.DrawingViews[1].ReferencedDocumentDescriptor.DisplayName + "found"; if (sh.DrawingViews.Count > 0) { modelName = sh.DrawingViews[1].ReferencedDocumentDescriptor.DisplayName; PrintObject printOb = new PrintObject(); if (printOb.deletePDF(modelName, m_PDFPath, ref logMessage, ref errMessage)) { //logMessage += "Deleted PDF: " + pair.Value.Value.ToString() + "\r\n"; //we already logged a message in the deletePDF function } else { logMessage += logMessage; errMessage += "Can not delete PDF Error1 in function FileUpdate\r\n"; return(false); } } } } } catch (Exception ex) { logMessage += logMessage; errMessage += "Can not delete PDF Error2 in function FileUpdate\r\n" + ex.Message + "\r\n"; return(false); } } return(true); } catch (Exception) { logMessage += logMessage; errMessage += errMessage; return(false); } }
// this routine was coded to use the ERP names instead of the part names // it needs to have a list of ERP names passed to it, each one matching its corresponding sheet in the IDW. // the routine actually doesn't care whether it gets passed Vault Names or Epicor Numbers, // it'll just name the pdfs accordingly // as of November 1 2017, it is no longer being used. public Boolean printToPDFNew(string idw, System.Collections.Generic.Dictionary <VDF.Vault.Currency.Entities.IEntity, Autodesk.DataManagement.Client.Framework.Vault.Currency.Properties.PropertyValue> propDict, string outputFolder, ref string errMessage, ref string logMessage) { { try { InventorApprentice.ApprenticeServerComponent oApprentice = new ApprenticeServerComponent(); InventorApprentice.ApprenticeServerDrawingDocument drgDoc; drgDoc = (InventorApprentice.ApprenticeServerDrawingDocument)oApprentice.Document; oApprentice.Open(idw); drgDoc = (InventorApprentice.ApprenticeServerDrawingDocument)oApprentice.Document; int pageCount = 1; List <string> assemblyFileNameList = new List <string>(); idwFile idwObject = new idwFile(); idwObject.sheetNames = new List <string>(); idwObject.idwName = idw; idwObject.pageCount = drgDoc.Sheets.Count; foreach (Sheet sh in drgDoc.Sheets) { if (sh.DrawingViews.Count > 0) { string modelName; string modelExtension; modelName = sh.DrawingViews[1].ReferencedDocumentDescriptor.DisplayName; modelExtension = System.IO.Path.GetExtension(modelName); bool matchFound = false; foreach (KeyValuePair <VDF.Vault.Currency.Entities.IEntity, VDF.Vault.Currency.Properties.PropertyValue> pair in propDict) { if (pair.Key.EntityMasterId != 0) { if (pair.Key.EntityName.ToString() == modelName) { modelName = System.IO.Path.GetFileNameWithoutExtension(pair.Value.Value.ToString()); //logMessage+= "\nModel Name: " + modelName + "\n\r"; matchFound = true; idwObject.sheetNames.Add(modelName); break; } } } if (!matchFound) { logMessage += @" " + "\r\n" + @" " + "No corresponding model found for " + modelName + @" " + "\r\n" + @" "; idwObject.sheetNames.Add("unmatchedfile"); pageCount++; //continue; } else { pageCount++; } } } string debugFileName = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\PrintPDFCommandLine\debug.txt"; using (StreamWriter writetext = new StreamWriter(debugFileName)) { writetext.WriteLine(AppSettings.Get("PrintPDFWorkingFolder").ToString()); } Process myProcess = new Process(); myProcess.StartInfo.UseShellExecute = false; myProcess.StartInfo.WorkingDirectory = AppSettings.Get("PrintPDFWorkingFolder").ToString(); myProcess.StartInfo.FileName = AppSettings.Get("PrintPDFExecutable").ToString(); myProcess.StartInfo.Arguments = @"""" + AppSettings.Get("PrintPDFPrinter").ToString() + @"""" + " " + @"""" + outputFolder + @"""" + " " + @"""" + AppSettings.Get("PrintPDFPS2PDF").ToString() + @"""" + " " + @"""" + AppSettings.Get("GhostScriptWorkingFolder").ToString() + @"""" + " " + @"""" + idw + @"""" + " " + (pageCount - 1) + " "; foreach (string sheetName in idwObject.sheetNames) { myProcess.StartInfo.Arguments += " " + @"""" + sheetName + @""""; } myProcess.StartInfo.CreateNoWindow = true; myProcess.Start(); myProcess.WaitForExit(); string argumentsFileName = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\PrintPDFCommandLine\arguments.txt"; using (StreamWriter writetext = new StreamWriter(argumentsFileName)) { writetext.WriteLine(myProcess.StartInfo.Arguments); } string returnFileName = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\PrintPDFCommandLine\" + AppSettings.Get("PrintPDFreturnFile").ToString(); int lineCount = System.IO.File.ReadLines(returnFileName).Count(); // after a successful run of PrintPDF, the file 'return.txt' should contain a // list of files printed, the number of lines matching the number of sheets in the idw if (!(lineCount == pageCount)) // if the drawing set has a sheet with no drawing views on it, for example if a sheet has only a BOM // this test will not be accurate. The routine will return an error even though the pages all printed ok // but because the page count does not equal the sheet count it will return a false error. // so I decided for now I will still log the error, but we won't return a fail status. { errMessage = System.IO.File.ReadAllText(returnFileName); } else { logMessage += idw + " printed successfully"; } errMessage = logMessage; return(true); } catch (Exception ex) { errMessage += "Unknown Error in printToPDF\r\n"; errMessage += ex.Message + "\r\n"; return(false); } } }
// this is an attempt to get rid of the extra command line step for printing pdfs. // it also uses the display names inside the idw for the pdf names rather than getting it from a Vault property. public Boolean printToPDF(string idw, string outputFolder, string pdfPrinterName, string psToPdfProgName, string ghostScriptWorkingFolder, ref string errMessage, ref string logMessage) { { try { // set log file location XmlConfigurator.Configure(); log4net.Repository.Hierarchy.Hierarchy h = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository(); foreach (IAppender a in h.Root.Appenders) { if (a is FileAppender) { FileAppender fa = (FileAppender)a; // Programmatically set this to the desired location here string logFileLocation = outputFolder + "PDFPrint.log"; // Uncomment the lines below if you want to retain the base file name // and change the folder name... //FileInfo fileInfo = new FileInfo(fa.File); //logFileLocation = string.Format(@"C:\MySpecialFolder\{0}", fileInfo.Name); fa.File = logFileLocation; fa.ActivateOptions(); break; } } InventorApprentice.ApprenticeServerComponent oApprentice = new ApprenticeServerComponent(); InventorApprentice.ApprenticeServerDrawingDocument drgDoc; oApprentice.Open(idw); drgDoc = (InventorApprentice.ApprenticeServerDrawingDocument)oApprentice.Document; int pageCount = 1; List <string> assemblyFileNameList = new List <string>(); idwFile idwFileToPrint = new idwFile(); idwFileToPrint.sheetNames = new List <string>(); idwFileToPrint.idwName = idw; idwFileToPrint.pageCount = drgDoc.Sheets.Count; foreach (Sheet sh in drgDoc.Sheets) { if (sh.DrawingViews.Count > 0) { string modelName; modelName = sh.DrawingViews[1].ReferencedDocumentDescriptor.DisplayName; // this doesn't work right on files with special characters. //modelName = Path.GetFileNameWithoutExtension(modelName); if (modelName.EndsWith(".ipt") || modelName.EndsWith(".iam")) { int index = modelName.LastIndexOf('.'); modelName = index == -1 ? modelName: modelName.Substring(0, index); } idwFileToPrint.sheetNames.Add(modelName); pageCount++; } } log.Info("Sheet Names All Read When Printing " + idwFileToPrint.idwName); string printer = pdfPrinterName; string pdfConverter = psToPdfProgName; string workingDir = ghostScriptWorkingFolder; string psFileName = ""; string pdfFileName = ""; try { InventorApprentice.ApprenticeDrawingPrintManager pMgr; drgDoc = (InventorApprentice.ApprenticeServerDrawingDocument)oApprentice.Document; pMgr = (InventorApprentice.ApprenticeDrawingPrintManager)drgDoc.PrintManager; pMgr.Printer = printer; int actualSheetIndex = 1; int modifiedSheetIndex = 1; foreach (Sheet sh in drgDoc.Sheets) { string modelName; //string modelExtension; if (sh.DrawingViews.Count > 0) // added to make sure sheet has at least one drawing view { modelName = sh.DrawingViews[1].ReferencedDocumentDescriptor.DisplayName; // this doesn't work right on files with special characters. //modelName = Path.GetFileNameWithoutExtension(modelName); if (modelName.EndsWith(".ipt") || modelName.EndsWith(".iam")) { int index = modelName.LastIndexOf('.'); modelName = index == -1 ? modelName : modelName.Substring(0, index); } string newName = ""; switch (sh.Orientation) { case PageOrientationTypeEnum.kLandscapePageOrientation: pMgr.Orientation = PrintOrientationEnum.kLandscapeOrientation; break; case PageOrientationTypeEnum.kDefaultPageOrientation: pMgr.Orientation = PrintOrientationEnum.kDefaultOrientation; break; case PageOrientationTypeEnum.kPortraitPageOrientation: pMgr.Orientation = PrintOrientationEnum.kPortraitOrientation; break; } pMgr.SetSheetRange(actualSheetIndex, actualSheetIndex); pMgr.PrintRange = PrintRangeEnum.kPrintSheetRange; pMgr.ScaleMode = InventorApprentice.PrintScaleModeEnum.kPrintBestFitScale; //if (more than one matching pdf name) if (idwFileToPrint.sheetNames.Where(x => x.Equals(idwFileToPrint.sheetNames[modifiedSheetIndex - 1])).Count() > 1) { newName = outputFolder + idwFileToPrint.sheetNames[modifiedSheetIndex - 1] + ".pdf"; if (System.IO.File.Exists(outputFolder + idwFileToPrint.sheetNames[modifiedSheetIndex - 1] + ".pdf")) { assemblyFileNameList.Add(newName); newName = outputFolder + idwFileToPrint.sheetNames[modifiedSheetIndex - 1] + "~" + 1 + ".pdf"; if (System.IO.File.Exists(newName)) { System.IO.File.Delete(newName); } System.IO.File.Move(outputFolder + idwFileToPrint.sheetNames[modifiedSheetIndex - 1] + ".pdf", newName); assemblyFileNameList.Add(newName); } } psFileName = outputFolder + idwFileToPrint.sheetNames[modifiedSheetIndex - 1] + ".ps"; pdfFileName = outputFolder + idwFileToPrint.sheetNames[modifiedSheetIndex - 1] + ".pdf"; // for some reason if a ps filename contains a comma it doesn't want to print. // we'll replace it with a tilde. if (psFileName.Contains(",")) { psFileName = psFileName.Replace(',', '~'); log.Warn("One or more characters replaced with '~' in " + pdfFileName); //logMessage += "One or more characters replaced with '~' in " + pdfFileName + "\r\n"; } if (psFileName.Contains("°")) { psFileName = psFileName.Replace('°', '~'); log.Warn("One or more characters replaced with '°' in " + pdfFileName); //logMessage += "One or more characters replaced with '°' in " + pdfFileName + "\r\n"; } pMgr.PrintToFile(psFileName); if (System.IO.File.Exists(psFileName)) { log.Info("PS file generated for " + psFileName); } else { log.Warn("PS file for " + psFileName + "could not be generated."); continue; // skip trying to create a pdf if we couldn't generate a ps } // notice: // gs doesn't seem to be able to handle the degree symbol // all filenames with a degree symbol will lose it when run through this script Process oProc = new Process(); // need the full path to the program if we want to set UseShellExecute to false ProcessStartInfo startInfo = new ProcessStartInfo(pdfConverter); startInfo.WorkingDirectory = workingDir; startInfo.Arguments = @"""" + psFileName + @"""" + " " + @"""" + pdfFileName + @""""; startInfo.CreateNoWindow = true; oProc.StartInfo = startInfo; oProc.StartInfo.UseShellExecute = false; oProc.Start(); oProc.WaitForExit(); if (assemblyFileNameList != null) { if (assemblyFileNameList.Count > 1) // combine multiple assembly drawings into one pdf file { // Open the input files PdfDocument inputDocument1 = new PdfDocument(); PdfDocument inputDocument2 = new PdfDocument(); if (System.IO.File.Exists(assemblyFileNameList[0])) { inputDocument1 = PdfReader.Open(assemblyFileNameList[0], PdfDocumentOpenMode.Import); } if (System.IO.File.Exists(assemblyFileNameList[1])) { inputDocument2 = PdfReader.Open(assemblyFileNameList[1], PdfDocumentOpenMode.Import); } // Create the output document PdfDocument outputDocument = new PdfDocument(); // Show consecutive pages facing. Requires Acrobat 5 or higher. outputDocument.PageLayout = inputDocument1.PageLayout; int count = Math.Max(inputDocument1.PageCount, inputDocument2.PageCount); for (int idx = 0; idx < count; idx++) { PdfPage page1 = new PdfPage(); PdfPage page2 = new PdfPage(); if (inputDocument1.PageCount > idx) { page1 = inputDocument1.Pages[idx]; page1 = outputDocument.AddPage(page1); } if (inputDocument2.PageCount > idx) { page2 = inputDocument2.Pages[idx]; page2 = outputDocument.AddPage(page2); } } if (System.IO.File.Exists(assemblyFileNameList[0])) { System.IO.File.Delete(assemblyFileNameList[0]); } // Save the document... while (!(System.IO.File.Exists(assemblyFileNameList[0]))) { string filename = assemblyFileNameList[0]; outputDocument.Save(filename); } // delete the temp file and clear the list if (System.IO.File.Exists(assemblyFileNameList[1])) { System.IO.File.Delete(assemblyFileNameList[1]); } assemblyFileNameList.Clear(); } } System.IO.File.Delete(psFileName); actualSheetIndex++; modifiedSheetIndex++; } else { actualSheetIndex++; // still need to increment sheet index, even if no drawing view was found // on current sheet... } // double check to make sure file got generated and saved properly. if (!System.IO.File.Exists(pdfFileName)) { log.Warn("No PDF Generated for " + pdfFileName); //logMessage += "No PDF Generated for " + pdfFileName + "\r\n"; } else { log.Info("PDF Generated for " + pdfFileName); } } } catch (Exception ex) { //errMessage += "PDF Generation Error in printToPDF\r\n"; //errMessage += ex.Message + "\r\n"; log.Error("PDF Generation Error in printToPDF"); log.Error(ex.Message); return(false); } } catch (Exception ex) { //errMessage += "IDW File Read Error in printToPDF\r\n"; //errMessage += ex.Message + "\r\n"; log.Error("IDW File Read Error in printToPDF"); log.Error(ex.Message); return(false); } return(true); } }
static int Main(string[] args) { // the first parameter passed to this program needs to be the name of the printer to print to. // the second one is the path to the folder to print the pdfs to // the third one is the path and name of the executable of the postscript to pdf converter // the rest of the parameters need to be in sets as follows: // 1. the full path to the idw file // 2. the number of pages in the idw file // 3. a list of filenames (the count matching the number of pages), one for each page in the idw // this program writes to a text file called return.txt that is created in the %appdata%\PrintPDFCommandLine directory. // it outputs each pdf filename on a line by itself as soon as it has successfully written it. string printer = ""; string outputFolder = ""; string pdfConverter = ""; string workingDir = ""; string IOFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\PrintPDFCommandLine\"; string returnFileName = IOFolder + "return.txt"; string callingParamsFileName = IOFolder + "callingparams.txt"; List <idwFile> idwFiles = new List <idwFile>(); try { if (System.IO.File.Exists(returnFileName)) { System.IO.File.Delete(returnFileName); } idwFile idw = new idwFile(); idw.sheetNames = new List <string>(); if (args == null) { using (System.IO.StreamWriter file = new System.IO.StreamWriter(returnFileName, true)) { file.WriteLine("Error: No arguments specified, aborting operation"); } Console.WriteLine("No arguments specified, aborting operation\n"); return(1); // printer not specified, nothing to print } printer = args[0]; // first argument is name of printer to print to outputFolder = args[1]; pdfConverter = args[2]; workingDir = args[3]; for (int argIndex = 4; argIndex < args.Count();) // the rest of the arguments are the pdf names to use for printing the idw sheets { idw.idwName = args[argIndex]; idw.pageCount = int.Parse(args[argIndex + 1]); argIndex += 2; int i = 0; for (i = argIndex; i < (argIndex + idw.pageCount); i++) { idw.sheetNames.Add(args[i]); using (System.IO.StreamWriter file = new System.IO.StreamWriter(callingParamsFileName, true)) { file.WriteLine(args[i]); if (System.IO.File.Exists(outputFolder + args[i] + ".pdf")) { System.IO.File.Delete(outputFolder + args[i] + ".pdf"); // delete any outdated files } } } argIndex = i; idwFiles.Add(idw); idw.sheetNames = new List <string>(); } } catch (Exception ex) { using (System.IO.StreamWriter file = new System.IO.StreamWriter(returnFileName, true)) { file.WriteLine("Error: Problems parsing arguments, aborting operation"); } Console.WriteLine("Problems parsing arguments, aborting operation\n"); return(1); } try { foreach (idwFile idw in idwFiles) { InventorApprentice.ApprenticeServerComponent oApprentice = new ApprenticeServerComponent(); InventorApprentice.ApprenticeServerDrawingDocument drgDoc; InventorApprentice.ApprenticeDrawingPrintManager pMgr; drgDoc = (InventorApprentice.ApprenticeServerDrawingDocument)oApprentice.Document; oApprentice.Open(idw.idwName); drgDoc = (InventorApprentice.ApprenticeServerDrawingDocument)oApprentice.Document; pMgr = (InventorApprentice.ApprenticeDrawingPrintManager)drgDoc.PrintManager; pMgr.Printer = printer; int actualSheetIndex = 1; int modifiedSheetIndex = 1; foreach (Sheet sh in drgDoc.Sheets) { string modelName; string modelExtension; if (sh.DrawingViews.Count > 0) // added to make sure sheet has at least one drawing view { modelName = sh.DrawingViews[1].ReferencedDocumentDescriptor.DisplayName; modelExtension = System.IO.Path.GetExtension(modelName); List <string> assemblyFileNameList = new List <string>(); string newName = ""; switch (sh.Orientation) { case PageOrientationTypeEnum.kLandscapePageOrientation: pMgr.Orientation = PrintOrientationEnum.kLandscapeOrientation; break; case PageOrientationTypeEnum.kDefaultPageOrientation: pMgr.Orientation = PrintOrientationEnum.kDefaultOrientation; break; case PageOrientationTypeEnum.kPortraitPageOrientation: pMgr.Orientation = PrintOrientationEnum.kPortraitOrientation; break; } pMgr.SetSheetRange(actualSheetIndex, actualSheetIndex); pMgr.PrintRange = PrintRangeEnum.kPrintSheetRange; pMgr.ScaleMode = InventorApprentice.PrintScaleModeEnum.kPrintBestFitScale; //if (more than one matching pdf name) if (idw.sheetNames.Where(x => x.Equals(idw.sheetNames[modifiedSheetIndex - 1])).Count() > 1) { newName = outputFolder + idw.sheetNames[modifiedSheetIndex - 1] + ".pdf"; if (System.IO.File.Exists(outputFolder + idw.sheetNames[modifiedSheetIndex - 1] + ".pdf")) { assemblyFileNameList.Add(newName); newName = outputFolder + idw.sheetNames[modifiedSheetIndex - 1] + "~" + 1 + ".pdf"; if (System.IO.File.Exists(newName)) { System.IO.File.Delete(newName); } System.IO.File.Move(outputFolder + idw.sheetNames[modifiedSheetIndex - 1] + ".pdf", newName); assemblyFileNameList.Add(newName); } } string psFileName = outputFolder + idw.sheetNames[modifiedSheetIndex - 1] + ".ps"; string pdfFileName = outputFolder + idw.sheetNames[modifiedSheetIndex - 1] + ".pdf"; // for some reason if a ps filename contains a comma it doesn't want to print. // we'll replace it with a tilde. if (psFileName.Contains(",")) { psFileName = psFileName.Replace(',', '~'); } if (psFileName.Contains("°")) { psFileName = psFileName.Replace('°', '~'); } pMgr.PrintToFile(psFileName); // notice: // gs doesn't seem to be able to handle the degree symbol // all filenames with a degree symbol will lose it when run through this script Process oProc = new Process(); // need the full path to the program if we want to set UseShellExecute to false ProcessStartInfo startInfo = new ProcessStartInfo(pdfConverter); //startInfo.WorkingDirectory = @"C:\Program Files\gs\gs9.18\bin\"; startInfo.WorkingDirectory = workingDir; startInfo.Arguments = @"""" + psFileName + @"""" + " " + @"""" + pdfFileName + @""""; startInfo.CreateNoWindow = true; oProc.StartInfo = startInfo; oProc.StartInfo.UseShellExecute = false; oProc.Start(); oProc.WaitForExit(); if (assemblyFileNameList != null) { if (assemblyFileNameList.Count > 1) // combine multiple assembly drawings into one pdf file { // Open the input files PdfDocument inputDocument1 = new PdfDocument(); PdfDocument inputDocument2 = new PdfDocument(); if (System.IO.File.Exists(assemblyFileNameList[0])) { inputDocument1 = PdfReader.Open(assemblyFileNameList[0], PdfDocumentOpenMode.Import); } if (System.IO.File.Exists(assemblyFileNameList[1])) { inputDocument2 = PdfReader.Open(assemblyFileNameList[1], PdfDocumentOpenMode.Import); } // Create the output document PdfDocument outputDocument = new PdfDocument(); // Show consecutive pages facing. Requires Acrobat 5 or higher. outputDocument.PageLayout = inputDocument1.PageLayout; int count = Math.Max(inputDocument1.PageCount, inputDocument2.PageCount); for (int idx = 0; idx < count; idx++) { PdfPage page1 = new PdfPage(); PdfPage page2 = new PdfPage(); if (inputDocument1.PageCount > idx) { page1 = inputDocument1.Pages[idx]; page1 = outputDocument.AddPage(page1); } if (inputDocument2.PageCount > idx) { page2 = inputDocument2.Pages[idx]; page2 = outputDocument.AddPage(page2); } } if (System.IO.File.Exists(assemblyFileNameList[0])) { System.IO.File.Delete(assemblyFileNameList[0]); } // Save the document... while (!(System.IO.File.Exists(assemblyFileNameList[0]))) { string filename = assemblyFileNameList[0]; outputDocument.Save(filename); } // delete the temp file and clear the list if (System.IO.File.Exists(assemblyFileNameList[1])) { System.IO.File.Delete(assemblyFileNameList[1]); } assemblyFileNameList.Clear(); } } using (System.IO.StreamWriter file = new System.IO.StreamWriter(returnFileName, true)) { file.WriteLine(pdfFileName); } System.IO.File.Delete(psFileName); actualSheetIndex++; modifiedSheetIndex++; } else { actualSheetIndex++; // still need to increment sheet index, even if no drawing view was found // on current sheet... } } } return(0); } catch (Exception x) { using (System.IO.StreamWriter file = new System.IO.StreamWriter(returnFileName, true)) { file.WriteLine("Error: Problems printing pdfs, aborting operation"); file.WriteLine(x.ToString()); } Console.WriteLine("Problems printing pdfs, aborting operation\n"); return(1); } }
static void Main(string[] args) { Console.BufferWidth = 300; Console.WindowWidth = 140; string msg = String.Format("coolOrange bcpMaker v{0}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version); Console.WriteLine(msg); Console.WriteLine("".PadRight(msg.Length, '*')); if (System.IO.File.Exists("bcpMaker.log")) { System.IO.File.Delete("bcpMaker.log"); } System.IO.File.AppendAllLines("bcpMaker.log", new string[] { msg }); if (!System.IO.File.Exists("config.xml")) { Console.WriteLine("config.xml file could not be found nearby the bcpMaker.exe"); Console.ReadKey(); return; } XmlDocument config = new XmlDocument(); try { config.Load("config.xml"); } catch (Exception ex) { Console.WriteLine(String.Format("Error loading config.xml: {0}", ex)); Console.ReadKey(); return; } var parameters = config.SelectSingleNode("//PARAMETERS"); string sourceFolder = parameters.Attributes["SourceFilesFolder"].Value; string targetFolder = parameters.Attributes["TargetBCPFolder"].Value; var ignore = config.SelectSingleNode("//IGNORE"); string ignoreFolder = ignore.Attributes["Folders"].Value; string ignoreFiles = ignore.Attributes["FileExtensions"].Value; var categoryRules = config.SelectNodes("//CATEGORYRULE"); System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("Source folder: {0} ", sourceFolder) }); System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("target folder: {0} ", sourceFolder) }); System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("ignore file extensions: {0} ", ignoreFiles) }); System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("ignore folder: {0} ", ignoreFolder) }); if (!System.IO.Directory.Exists(sourceFolder)) { Console.WriteLine(String.Format("source folder '{0}' does not exist", sourceFolder)); Console.ReadKey(); return; } try { System.IO.Directory.CreateDirectory(targetFolder); } catch { Console.WriteLine(String.Format("target folder '{0}' could not be created", targetFolder)); Console.ReadKey(); return; } #region apprentice server initialization ApprenticeServerComponent _invApp = new ApprenticeServerComponent(); DesignProject InventorProject = _invApp.DesignProjectManager.ActiveDesignProject; List <string> libraryFolders = new List <string>(); string ccPath = InventorProject.ContentCenterPath; libraryFolders.Add(ccPath.Replace(sourceFolder, "")); string workSpace = InventorProject.WorkspacePath; workSpace = workSpace.Replace(sourceFolder, ""); var libraryPaths = InventorProject.LibraryPaths; msg = String.Format("Using Inventor Project File '{0}'", InventorProject.FullFileName); Console.WriteLine(msg); System.IO.File.AppendAllLines("bcpMaker.log", new string[] { msg }); ProjectPaths libPaths = InventorProject.LibraryPaths; foreach (ProjectPath libpath in libPaths) { libraryFolders.Add(libpath.Path.TrimStart('.').Replace("\\", "/")); } #endregion List <string> files = new List <string>(); Console.WriteLine("Scanning folders..."); GetAllFilesFromFolderRecursively(sourceFolder, files, ignoreFiles, ignoreFolder); Console.WriteLine(String.Format("\rCollected files {0}", files.Count).PadRight(Console.BufferWidth, ' ')); #region adding files to BCP package Console.WriteLine("Adding files to BCP package..."); var bcpSvcBuilder = new BcpServiceBuilder { Version = BcpVersion._2016 }; bcpSvcBuilder.SetPackageLocation(targetFolder); var bcpSvc = bcpSvcBuilder.Build(); int counter = 1; Dictionary <string, FileObject> bcpInventorFiles = new Dictionary <string, FileObject>(StringComparer.OrdinalIgnoreCase); foreach (string file in files) { string vaultTarget = file.Replace(sourceFolder, "$").Replace("\\", "/"); bool isLibrary = libraryFolders.Any(lf => vaultTarget.Contains(lf.Replace("\\", "/"))); var bcpFile = bcpSvc.FileService.AddFile(vaultTarget, file, isLibrary); string extension = System.IO.Path.GetExtension(file); foreach (XmlNode categoryRule in categoryRules) { var fileExtensions = categoryRule.SelectSingleNode("//FILEEXTENSION"); var category = categoryRule.SelectSingleNode("//CATEGORY"); var lifecycleDefinition = categoryRule.SelectSingleNode("//LIFECYCLEDEFINITON"); var state = categoryRule.SelectSingleNode("//STATE"); var revision = categoryRule.SelectSingleNode("//REVISION"); var revisionDefinition = categoryRule.SelectSingleNode("//REVISIONDEFINITION"); if (fileExtensions != null && (fileExtensions.InnerText == "" || fileExtensions.InnerText.Split(',').Contains(extension))) { if (category != null && category.InnerText != "") { bcpFile.Category = category.InnerText; } string stateName = state != null ? state.InnerText : ""; if (lifecycleDefinition != null && lifecycleDefinition.InnerText != "") { bcpFile.LatestIteration.Setstate(lifecycleDefinition.InnerText, stateName); } bcpFile.LatestRevision.SetRevisionDefinition(revisionDefinition != null ? revisionDefinition.InnerText : "", revision != null ? revision.InnerText : ""); break; } } if (file.ToLower().EndsWith("iam") || file.ToLower().EndsWith("ipt") || file.ToLower().EndsWith("idw") || file.ToLower().EndsWith("ipn") || file.ToLower().EndsWith("dwg")) { bcpInventorFiles.Add(file, bcpFile); System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("Adding to reference check list: {0}", file) }); } msg = String.Format("\rAdding file {0} of {1} to BCP package", counter++, files.Count()); Console.Write(msg); } Console.WriteLine(String.Format("\rAdded files {0}", bcpSvc.EntitiesTable.Vault.Statistics.Totfiles).PadRight(Console.BufferWidth, ' ')); #endregion var inventorFiles = files.Where(file => file.ToLower().EndsWith("iam") || file.ToLower().EndsWith("ipt") || file.ToLower().EndsWith("idw") || file.ToLower().EndsWith("ipn") || file.ToLower().EndsWith("dwg")).ToList(); Console.WriteLine("Building references for Inventor files..."); counter = 0; foreach (string iFile in inventorFiles) { msg = String.Format("\r{1}/{2}: Building references and properties for {0}", iFile, counter++, inventorFiles.Count); Console.Write(msg.PadRight(Console.BufferWidth, ' ')); ApprenticeServerDocument doc = null; try { doc = _invApp.Open(iFile); } catch (Exception ex) { msg = String.Format("\r\nOpen ERROR!File {0} could not be opened", iFile); Console.WriteLine(msg); System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("{0}\r\n{1}", msg, ex) }); continue; } var bcpParent = bcpInventorFiles[iFile]; string databaseRevisionID = ""; string lastSavedLocation = ""; object indices = null; object oldPaths = null; object currentPaths = null; try { doc._GetReferenceInfo(out databaseRevisionID, out lastSavedLocation, out indices, out oldPaths, out currentPaths, true); } catch (Exception ex) { msg = String.Format("\r\nRead ERROR!References for file {0} could not retrieved", iFile); Console.WriteLine(msg); System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("{0}\r\n{1}", msg, ex) }); continue; } string[] refs = currentPaths as string[]; int[] idx = indices as int[]; for (int i = 0; i < refs.Count(); i++) { string child = refs[i]; if (child == null) { msg = String.Format("\r\nReference Warning!Reference {0} not found for assembly {1}", (oldPaths as string[])[i], iFile); Console.WriteLine(msg); System.IO.File.AppendAllLines("bcpMaker.log", new string[] { msg }); continue; } System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("Reference {0}", child) }); if (bcpInventorFiles.ContainsKey(child)) { var bcpChild = bcpInventorFiles[child]; var assoc = bcpParent.LatestIteration.AddAssociation(bcpChild.LatestIteration, AssociationObject.AssocType.Dependency); assoc.refId = idx[i].ToString(); assoc.needsresolution = true; } else { msg = String.Format("\rPackage ERROR!Child {0} not in bcp package for assembly {1}", (oldPaths as string[])[i], iFile); Console.WriteLine(msg); System.IO.File.AppendAllLines("bcpMaker.log", new string[] { msg }); } } string propName = ""; try { foreach (PropertySet propSet in doc.PropertySets) { foreach (Property prop in propSet) { propName = prop.Name; if (!propName.Equals("Thumbnail") && !propName.Equals("Part Icon") && prop.Value != null) { bcpParent.LatestIteration.AddProperty(prop.DisplayName, prop.Value.ToString()); } } } } catch (Exception ex) { msg = String.Format("\r\nProperty ERROR!Property {1} for file {0} could not be retrieved", iFile, propName); Console.WriteLine(msg); System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("{0}\r\n{1}", msg, ex) }); } doc.Close(); } _invApp.Close(); bcpSvc.Flush(); System.Diagnostics.Process.Start(targetFolder); }