Use VBA to plot idw to pdf

Use VBA to plot idw to pdf

Anonymous
Not applicable
7,385 Views
47 Replies
Message 1 of 48

Use VBA to plot idw to pdf

Anonymous
Not applicable
Hi,



I've been looking into getting VBA to plot an idw to pdf automatically. From what I've found I can either have Adobe prompt for the save file location everytime, or never. Is there a way to have the file location specified within the macro code? There are two locations that I save pdf's and I'd like to have one macro save to one location, and another macro which saves to the second location. So it would be great if the file location was already specified by the marco. Currently I've been using the .SubmitPrint() method:




Public Sub PlotPDF()

If ThisApplication.ActiveDocument.DocumentType = kDrawingDocumentObject Then



Dim oDrgDoc As DrawingDocument

Set oDrgDoc = ThisApplication.ActiveDocument





' Set reference to drawing print manager

Dim oDrgPrintMgr As DrawingPrintManager

Set oDrgPrintMgr = oDrgDoc.PrintManager



' Set the printer name

oDrgPrintMgr.Printer = "Adobe PDF"



'Set the paper size , scale and orientation

oDrgPrintMgr.ScaleMode = kPrintBestFitScale

oDrgPrintMgr.PaperSize = kPaperSizeLetter

oDrgPrintMgr.PrintRange = kPrintAllSheets

oDrgPrintMgr.Orientation = kLandscapeOrientation

oDrgPrintMgr.AllColorsAsBlack = True

oDrgPrintMgr.SubmitPrint



End If

End Sub



============================



Any ideas?



Thanks!



-Andrew

Inventor 11 SP4

0 Likes
7,386 Views
47 Replies
Replies (47)
Message 21 of 48

AlexFielder
Advisor
Advisor
Looking at your screenshot, why does it show PlotPdf twice?

Also, you can get it to run by hitting Alt+F11 then click into the PlotPdf function and either hit F5 or click on the "Run" button in the vba editor.

I think there is a way you can get the macro to load every time you start Inventor, but I never managed to figure it out. (and I can't remember where I read about it to provide any linkage)
0 Likes
Message 22 of 48

karthur1
Mentor
Mentor


There was an extra



Sub PlotPDF()

End Sub



in what I copied/Paste. Don't know where that came from. That is probably why two PlotPDF were showing in the list. I redid the copy/paste and that is gone now.



Now, if I run the code from the Visual Basic editor (by clicking run in editor), I get a "User-defined type not defined" error (see attached).



When I run from Inventor, the "run" button is still not available.



Thanks

0 Likes
Message 23 of 48

Anonymous
Not applicable
I have attached a module contain code that will not only load the macro but will run it as well. The code is not completely error trapped and expects to find the macro file in the same folder as the addin. I use this routine (RunMacro) is ButtonDefinition OnExecute event procedures.
0 Likes
Message 24 of 48

AlexFielder
Advisor
Advisor
If you look at your video, it's complaining that you haven't defined the PDFCreator.clsPDFCreator class

I would suggest you check that your references (to the pdfcreator) are still intact. See attached.
0 Likes
Message 25 of 48

karthur1
Mentor
Mentor


I checked the references and there is a PDFCreator in the list, but it is not checked. When I check it, I get an error saying "Name conflicts with existing module, project, or object library".



I have the latest version of pdfcreator installed (version 0.9.8).



Not sure what to do now.

0 Likes
Message 26 of 48

AlexFielder
Advisor
Advisor
I'm reviving this thread because, annoyingly, my code doesn't seem to like printing the first sheet of a DrawingDocument (DrawDoc).

I'm certain it has to do with the initialization of the PDFCreator Class, but I can't figure out what I'm doing wrong. Can anyone help?

Rgds,

Veg.
0 Likes
Message 27 of 48

Anonymous
Not applicable
Bob,
We are looking to export IDW to TIF. Was wondering if you may be able to share more info about your macro or possibly some example code or TIF files that were created with it ?

Thanks,
Doug

> {quote:title=Guest wrote:}{quote}
> I had tried using the PrintToFile method before when I was writing
> my plot2pdf macro sometime ago. I remember that it did not work
> (couldn't open the files). Found another pdf printer that I could
> pass it the filename to print to without using the printtofile
> method. It's called win2pdf. My macro also then runs a ghostscript
> command to also create a monochrome tiff file from the pdf.
>
> Bob S.
0 Likes
Message 28 of 48

Anonymous
Not applicable
Doug,

Below you will find my current macro I use that outputs both pdf and
tiff files. The tiff is made by converting the pdf file using
ghostscript, so you will have to install that if you don't have it
already. I just recently converted this from using Win2pdf to
make the pdf file, as it seems Autodesk has finally fixed their
output to a level that I can accept. There may be some variables
that aren't used anymore, and I might do more with building the
filenames than you need. Should be able to figure it all out though.
Currently, it does not work well if you have spaces in the path
or filename (for the ghostscript command), and since changing to the
save copy as pdf option, I seem to get some random crashes during
the pdf creation phase, after the macro has run a few times per
session. Not sure who's fault that is? I'm currently using IV2009
32 bit on XP. This macro only saves the currently active sheet to
pdf. You can probably change that if you want. Not sure if ghostscript
handles creating multipage tiff files from pdf or not? No error checking
in this puppy either. Enjoy!

Bob S.

Doug6598 wrote:
> Bob,
> We are looking to export IDW to TIF. Was wondering if you may be able to share more info about your macro or possibly some example code or TIF files that were created with it ?
>
> Thanks,
> Doug
>
>> {quote:title=Guest wrote:}{quote}
>> I had tried using the PrintToFile method before when I was writing
>> my plot2pdf macro sometime ago. I remember that it did not work
>> (couldn't open the files). Found another pdf printer that I could
>> pass it the filename to print to without using the printtofile
>> method. It's called win2pdf. My macro also then runs a ghostscript
>> command to also create a monochrome tiff file from the pdf.
>>
>> Bob S.

Public Sub SaveDrawing_PDF()
Dim FullFilename As String
Dim PDFFilename As String
Dim TIFFilename As String
Dim Path As String
Dim myDate As String
myDate = Format(Month(Date), "0#") & Format(Day(Date), "0#") & Right(Year(Date), 2)

Dim mySheet As Sheet
Dim mySheetHgt As Double
Dim mySheetWid As Double
Dim oDrawDoc As DrawingDocument
Set oDrawDoc = ThisApplication.ActiveDocument
' Get a reference to the "Design State" property.
Dim oPropSets As PropertySets
Set oPropSets = oDrawDoc.PropertySets
Dim oProp As Property
Set oProp =
oPropSets.Item("{32853F0F-3444-11d1-9E93-0060B03C1CA6}").ItemByPropId(kDesignStatusDesignTrackingProperties)
Dim DesignState As String
Select Case oProp.Value
Case 0 To 2
DesignState = "_PENDING_"
Case 3
DesignState = "_FINAL_"
End Select

Dim sNum As Integer
Dim sCount As Integer
Set mySheet = oDrawDoc.ActiveSheet
mySheetHgt = mySheet.height
mySheetWid = mySheet.Width
'MsgBox "Sheet Size: " & mySheetHgt & " x " & mySheetWid
'Set mySheet = oDrawDoc.Sheets.Item(1) '1 would become the sheet num passed
sCount = oDrawDoc.Sheets.Count
sNum = SheetPosition(mySheet)
'just add the sheet number to all.
PDFFilename = Left(oDrawDoc.FullFilename, Len(oDrawDoc.FullFilename) - 4) & "_SHT_" & sNum & "_OF_" & sCount &
DesignState & myDate & ".pdf"
TIFFilename = Left(oDrawDoc.FullFilename, Len(oDrawDoc.FullFilename) - 4) & "_SHT_" & sNum & "_OF_" & sCount &
DesignState & myDate & ".tif"
'Code here to use Save Copy As PDF
' Get the PDF translator Add-In.
Dim PDFAddIn As TranslatorAddIn
Set PDFAddIn = ThisApplication.ApplicationAddIns.ItemById("{0AC6FD96-2F4D-42CE-8BE0-8AEA580399E4}")
Dim oContext As TranslationContext
Set oContext = ThisApplication.TransientObjects.CreateTranslationContext
oContext.Type = kFileBrowseIOMechanism
' Create a NameValueMap object
Dim oOptions As NameValueMap
Set oOptions = ThisApplication.TransientObjects.CreateNameValueMap
' Create a DataMedium object
Dim oDataMedium As DataMedium
Set oDataMedium = ThisApplication.TransientObjects.CreateDataMedium
' Check whether the translator has 'SaveCopyAs' options
If PDFAddIn.HasSaveCopyAsOptions(oDrawDoc, oContext, oOptions) Then
' Options for drawings...
oOptions.Value("All_Color_AS_Black") = 0
'oOptions.Value("Remove_Line_Weights") = 1
'oOptions.Value("Vector_Resolution") = 1
'oOptions.Value("Sheet_Range") = kPrintAllSheets
'oOptions.Value("Custom_Begin_Sheet") = 2
'oOptions.Value("Custom_End_Sheet") = 4
End If
'Set the destination file name
oDataMedium.FileName = PDFFilename
'Publish document.
Call PDFAddIn.SaveCopyAs(oDrawDoc, oContext, oOptions, oDataMedium)
'Shell command to convert pdf to tif:
Dim RetVal
Dim Cmdline As String
Cmdline = "C:\gs\gs8.13\bin\gswin32c -q -dNOPAUSE -sDEVICE=tiffg4 -r200 -sOutputFile="
Cmdline = Cmdline & TIFFilename & " " & PDFFilename & " -c quit"
Debug.Print Cmdline
RetVal = Shell(Cmdline, vbNormalFocus)
End Sub
0 Likes
Message 29 of 48

Anonymous
Not applicable
Bob,
Thanks for posting the code. I'm still working to get it functional, it outputs the pdf but not the tif (yet).

Appreciate the response.

Doug
0 Likes
Message 30 of 48

Anonymous
Not applicable
You need to make sure you have ghostscript installed and that it
is compiled with the tiff output drivers installed, and you might
need to modify the path to the ghostscript program that I have
embedded in the code to match your installed location. And lastly,
make sure your path to the pdf file has no spaces in it (including
the pdf filename itself.

I just recently downloaded and installed the latest ghostscript,
versions 8.70 and it had the tiff output drivers compiled in.

Doug6598 wrote:
> Bob,
> Thanks for posting the code. I'm still working to get it functional, it outputs the pdf but not the tif (yet).
>
> Appreciate the response.
>
> Doug
0 Likes
Message 31 of 48

Anonymous
Not applicable
You may also want to make sure to get the latest 8.70 version
of ghostscript, as I was running into a few isolated cases
where ghostscript would just choke on the pdf file, apparently
due to some of the embedded fonts in Inventor generated
pdfs, but I tried the 8.70 version and it seems to work on these
ones with no problems.

Bob

Bob S. wrote:
> You need to make sure you have ghostscript installed and that it
> is compiled with the tiff output drivers installed, and you might
> need to modify the path to the ghostscript program that I have
> embedded in the code to match your installed location. And lastly,
> make sure your path to the pdf file has no spaces in it (including
> the pdf filename itself.
>
> I just recently downloaded and installed the latest ghostscript,
> versions 8.70 and it had the tiff output drivers compiled in.
>
> Doug6598 wrote:
>> Bob,
>> Thanks for posting the code. I'm still working to get it functional, it outputs the pdf but not the tif (yet).
>>
>> Appreciate the response.
>>
>> Doug
0 Likes
Message 32 of 48

Anonymous
Not applicable
Hi
Did you ever found a solution?

I have tried your code - and found same problem. I am not using the RetrievePE and RetrievRev because it dosn't fit my title block.
Have you checked the outName to change for each sheet? If I do:
.cOption("AutosaveFilename") = outName & numsheets
I get all sheets printed!

What I now would like to do is to combine these to one pdf. I can do it in word and excel with a .cCombineAll but seems not to work here.

Any help, please.

Regards Claus
0 Likes
Message 33 of 48

AlexFielder
Advisor
Advisor
Hi Claus,
Unfortunately I haven't found a solution to the PDFCreator issue - and I haven't spent any time on it lately as it works 90% of the time - and the times it doesn't, simply ending the PDFCreator process is enough to stop it from binning the whole Inventor session.

As far as combining all sheets into one .pdf file goes, it seems like it would be possible to combine the pages into one .pdf file if you simply held off committing the print until all sheets had been added to the PDFCreator queue.

At what stage do you call the .cCombineAll in the other apps you mention?

As an aside; Assuming I can get it working 100% of the time, I'm actually planning on porting this whole thing to .NET - (when I get the time that is) - as I have a number of other tools I want to implement.
0 Likes
Message 34 of 48

Anonymous
Not applicable
Hi Veg

I have used the code from this source:

http://www.excelguru.ca/node/95

and it nicely puts the prints in the print queue until they gets combined.

I haven't succeed to do the same in Inventor, because the SubmitPrint overwrites in the queue.
I have put the combine part outside the loop.

Regards Claus
0 Likes
Message 35 of 48

Anonymous
Not applicable
OK, found the issue.
The SubmitPrint did'nt overwrite the queue, but I had cClearCache inside the For..Next, clearing the queue. So moving that up front did the trick. And the sheets combines nicely into one pdf.

Regards Claus
0 Likes
Message 36 of 48

AlexFielder
Advisor
Advisor
That's excellent, would you care to share your implementation so I can see what you've done differently?
0 Likes
Message 37 of 48

Anonymous
Not applicable
Here you are:

Code starts-----------------

Public Sub PlotPdf()
On Error GoTo Err_Control

Dim killit
Dim numsheets As Integer
Dim InitPrinter

numsheets = 0

' Set reference to active drawing
Dim oDrgDoc As DrawingDocument
Set oDrgDoc = ThisApplication.ActiveDocument

' Set reference to drawing print manager
Dim oDrgPrintMgr As DrawingPrintManager
Set oDrgPrintMgr = oDrgDoc.PrintManager

'Read printer so it can be set back
InitPrinter = oDrgPrintMgr.Printer

If ThisApplication.ActiveDocument.DocumentType = kDrawingDocumentObject Then
Set PDFCreator1 = CreateObject("PDFCreator.clsPDFCreator")
With PDFCreator1
If .cStart("/NoProcessingAtStartup") = False Then
killit = Shell("taskkill /f /im PDFCreator.exe", VbAppWinStyle.vbHide)
MsgBox ("There was an error starting the pdf printer, please try (click) again!")
Debug.Print "Can't initialize PDFCreator."
Exit Sub
End If
End With

'Debug.Print "PDFCreator initialized."

'Set some settings and clear queue
With PDFCreator1
.cOption("UseAutosave") = 1
.cOption("UseAutosaveDirectory") = 1
.cOption("AutosaveFormat") = 0 ' 0 = PDF
.cClearCache
End With

' Set the printer to PDFCreator
oDrgPrintMgr.Printer = "PDFCreator"

Dim sht As Sheet

For Each sht In oDrgDoc.Sheets
sht.Activate
'Set the paper size , scale and orientation
oDrgPrintMgr.ScaleMode = kPrintFullScale ' kPrintBestFitScale
' Change the paper size to a custom size. The units are in centimeters.
Dim shtsize As Long
Dim shtorientation As Long
shtsize = sht.Size
shtorientation = sht.Orientation
oDrgPrintMgr.PaperSize = kPaperSizeCustom
If shtsize = 9993 Then ' A0
oDrgPrintMgr.PaperHeight = 84.1
oDrgPrintMgr.PaperWidth = 118.9
ElseIf shtsize = 9994 Then ' A1
oDrgPrintMgr.PaperHeight = 59.4
oDrgPrintMgr.PaperWidth = 84.1
ElseIf shtsize = 9995 Then ' A2
oDrgPrintMgr.PaperHeight = 42
oDrgPrintMgr.PaperWidth = 59.4
ElseIf shtsize = 9996 Then ' A3
oDrgPrintMgr.PaperHeight = 29.7
oDrgPrintMgr.PaperWidth = 42
ElseIf shtsize = 9997 Then ' A4
oDrgPrintMgr.PaperHeight = 21
oDrgPrintMgr.PaperWidth = 29.7
End If
oDrgPrintMgr.PrintRange = kPrintCurrentSheet
If shtorientation = 10242 Then 'Landscape
oDrgPrintMgr.Orientation = kLandscapeOrientation
ElseIf shtorientation = 10243 Then 'Portrait
oDrgPrintMgr.Orientation = kPortraitOrientation
End If

oDrgPrintMgr.AllColorsAsBlack = True
oDrgPrintMgr.Rotate90Degrees = True

With PDFCreator1
.cOption("AutosaveDirectory") = "\\Data\PMC\PDF-arkiv\Dokumentation-til-godkendelse\"
.cOption("AutosaveFilename") = TegnNr & "_" & Rev 'Got this from another part of code
End With

oDrgPrintMgr.SubmitPrint

Sleep 1000

numsheets = numsheets + 1
Next
Else
MsgBox ("You aren't using an Inventor drawing!")
Exit Sub
End If

'Wait until all prints are in queue
Do Until PDFCreator1.cCountOfPrintjobs = numsheets
DoEvents
Sleep 1000
Loop

'Combine sheets in queue to one pdf
With PDFCreator1
.cCombineAll
.cPrinterStop = False
End With

'Wait until job done
Do Until PDFCreator1.cCountOfPrintjobs = 0
DoEvents
Sleep 1000
Loop

'Set back to first sheet and set printer back
oDrgDoc.Sheets(1).Activate
oDrgPrintMgr.Printer = InitPrinter

'Clean up
PDFCreator1.cClose
killit = Shell("taskkill /f /im PDFCreator.exe", VbAppWinStyle.vbHide)
Set oDrgDoc = Nothing
Set oDrgPrintMgr = Nothing

Exit_Here:
Exit Sub
Err_Control:
Select Case Err.Number
'Add your Case selections here
'Case Is = 1000
'Handle error
'Err.Clear
'Resume Exit_Here
Case Else
MsgBox Err.Number & ", " & Err.Description, , "PlotPdf"
Err.Clear
Resume Exit_Here
End Select
End Sub

Code ends------------------------

(I don't know how to set code tags)

As far as I have tested it, it works fine - and print out all sheets in one.

Best regards
Claus
0 Likes
Message 38 of 48

AlexFielder
Advisor
Advisor
Hi Claus,
Thanks for sharing your solution.

You can set code tags by putting { code } before and after your code. Without spaces obviously.

Following on from my post the other day, I have turned my implementation of this into an add-in. I also found the site you linked to very handy as (I think) I've managed to fix the error I had whereby sometimes files wouldn't print in time meaning they got lost from the queue. The piece of code that checks for file completion is: -

{code}
'Wait until the file shows up before closing PDF Creator
Do
DoEvents
Loop Until Dir(sPDFPath & sPDFName) = sPDFName
{code}

I am willing to share both the source and completed .dll for testing/comment if you like?
0 Likes
Message 39 of 48

Anonymous
Not applicable
Hi Veg

Did you also read this:

http://www.excelguru.ca/node/87

Reg. AddIns I don't have experience with that, so I won't be in a position to test/use.
I have put the code (among others) in a .ivb that all installations reference to, and that works fine for us.

If you ever manage to the .Net solution please let me know.

This thread and especially your contribution has been most helpfull.

Reg. Claus Edited by: cll@pmctechnology.dk on Dec 3, 2009 2:11 PM
0 Likes
Message 40 of 48

AlexFielder
Advisor
Advisor
You're welcome Claus. As far as that link is concerned, I had wondered what that line was for in the COM Example that you can install when installing PDFCreator - now I know. 🙂

For your digestion, attached is my VB .NET Express 2008 Solution. The Add-in is included in one of the subfolders, but given the somewhat convoluted steps necessary to install it manually, I might re-package it as an installer if I get time.

For those that are interested in trying my add-in, you need to regasm.exe /codebase the .dll file in order to have it load on demand within Inventor. I think the /codebase switch is normally for 64-bit applications, but for some reason add-ins created using the VB.NET Express 2008 Inventor Add-in template I have installed need it as well.

This code also outputs the resultant .pdf files to "C:\Temp\test_pdfs" and at the moment I don't have any means of checking that the folder exists so you'll likely get an unhandled expection error or similar if you try and run it without that directory already created.

Regards,

Veg.
0 Likes