(iLogic) How to insert a watermark into .idw exported PDF

(iLogic) How to insert a watermark into .idw exported PDF

JoãoASilva
Advocate Advocate
3,304 Views
9 Replies
Message 1 of 10

(iLogic) How to insert a watermark into .idw exported PDF

JoãoASilva
Advocate
Advocate

Hello all! 😀

 

Since I've been around this forum I learned alot, and I want to give back something.

I'll show you how to insert a watermark in a PDF file, when exporting from a drawing.

Since Inventor doesn't have a native tool, this is clearly a workaround.

 

I'm assuming you already have an iLogic code to export a sheet to PDF.

 

For this you will need:

- Inventor;

- Image editor program (GIMP, PhotoShop, etc)

 

PDFConfidential.png

This is a screenshot from the exported PDF file.

 

Size, color, letter type, etc..., can be changed as you wish, because we will use a .PNG image with transparent background.

 

 

 

 

 

 

 

 

 

 

 

  1.  Create an image on your image editor program, with the size of the sheet you use and transparent background. (A3 = 1684×1191 pixels);
  2. Create text, create images or insert them. This image will be layered on top of your drawing;
  3. Important: Set the opacity of your image/text to around 5%;
  4. Export to .png while maintaining the transparent background;
  5. On you Inventor make a copy of your border and edit the copy;

Borders.pngI have the "A2_Controlar_template_border", and made a copy and renamed it to "A2_Watermark".

 

 

 

 

 

 

 

 

 

 

     6. Edit this copy and add the image you created, dimensionate it and bring it forward;

Insert_Image.png

Image.png

 

You can send backwards, that's up to personal taste.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

     7. Once you have both borders, we can proceed to the iLogic code, wich is pretty simple:

 

Dim oDrawDoc As DrawingDocument = ThisApplication.ActiveDocument
Dim oSheet As Sheet = oDrawDoc.ActiveSheet
Dim oBorder As Border = oSheet.Border

' Check sheet size
If ActiveSheet.Size = "A2" Then

	'['Insert A2 Watermark
If ActiveSheet.Border = "A2_Border" Then
	oBorder.Delete
	ActiveSheet.Border = "A2_Watermark"
End If
	']
	
	'['Export PDF
	'Insert the iLogic you use to export to PDF
	']
	
	'['Remove A2 Watermark
	oBorder.Delete
	ActiveSheet.Border = "A2_Border"
	']

	Exit Sub
End If


'Check sheet size
If ActiveSheet.Size = "A3" Then

	'['Insert A3 Watermark
If ActiveSheet.Border = "A3_Border" Then
	oBorder.Delete
	ActiveSheet.Border = "A3_Watermark"
End If
	']

	'['Export PDF
	'Insert the iLogic you use to export to PDF
	']

	'['Remove A3 Watermark
	oBorder.Delete
	ActiveSheet.Border = "A3_Border"
	']
	
	Exit Sub
End If


MessageBox.Show("Sheet size must be A2 or A3!")',"Sheet size error:",vbOKOnly)
Exit Sub

Change "A2_Border" and "A3_Border" to the name of your border, the one without watermark.

Change "A2_Watermark" and "A3_Watermark" to the name of your border with watermark.

 

And that's it!

You can use the drawing sheet without any image or text in front.

But every time you run the rule to export, it will insert the new border, export and then restore the normal one.

 

 Notes:

- This is a workaround that really works for me, but others might export using different methods.

- My way of exporting to PDF is very specific, hence why my code isn't there.

 

Hope it helps! 😊

 

João Silva

Mechanical Engineer

 

Accepted solutions (1)
3,305 Views
9 Replies
Replies (9)
Message 2 of 10

WCrihfield
Mentor
Mentor

First of all, thanks for posting your code. That's pretty cool.

You should probably post something like (a direct answer to an unasked question) this in your Contributions section, under your Public Profile.

This area is mostly for asking questions, asking for help, etc, that require others to respond to.

You should probably mark your original post as 'Accept As Solution', or post a second time and mark it as the solution to remove it from the unanswered questions list.

Just a thought.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes
Message 3 of 10

Darkforce_the_ilogic_guy
Advisor
Advisor

I have made a similar code..my code can print an hole project to PDF. I could not get it transpar.... but I did make a picture and remove all the fill inside Anmærkning 2020-02-01 220100.png

 

then my program Will simple open all document add the Watermark.. and Print the PDF to an time(day) stamp folder 

I even make the program enble to continue there it left off ... if inventor crashes.

0 Likes
Message 4 of 10

JoãoASilva
Advocate
Advocate
Accepted solution

Just to close an open thread.

João Silva

Mechanical Engineer

 

Message 5 of 10

Jason.Rugg
Collaborator
Collaborator

@JoãoASilva @WCrihfield Trying to use this code but I dont use A2 or A3 psheet sizes, I use a custom size, so can the sheet check be removed or modified to accommodate "Custom Size (inches)"?

0 Likes
Message 6 of 10

WCrihfield
Mentor
Mentor

Hi @Jason.Rugg.  Here is something I just threw together that may help you out with that.  It is a bit more complicated looking, but includes extra error proofing code and separates the routines out into their own Subs to make it more modular.  I also did not include the actual code for exporting the drawing to a PDF, because there are tons of examples of that code here on the forums, and everyone seems to have their own custom needs in that area.  There are multiple ways to do the process of changing the borders out, then back again, but in my example I am just using a separated out sub routine which asks for the DrawingDocument you want it to target and the name of the BorderDefinition you want to change all the sheets to, as input variables.  You might also be able to use a Transaction to contain all the initial border changes, then after the PDF export, you may be able to UNDO the border changes.  Not sure if that would work with the PDF export in there after that event, and that soon afterwards though.

Here is what I have right now:

Sub Main
	If ThisApplication.ActiveDocumentType <> DocumentTypeEnum.kDrawingDocumentObject Then
		MsgBox("A Drawing Document must be active for this rule (" & iLogicVb.RuleName & ") to work. Exiting.", vbCritical, "iLogic")
		Exit Sub
	End If
	Dim oDDoc As DrawingDocument = ThisApplication.ActiveDocument
	Dim oOriginalActiveSheet As Sheet = oDDoc.ActiveSheet
	'<<<< EDIT NAMES TO MATCH YOUR SITUATION >>>>
	Dim oStandardBorderDefName As String = "Border Without Watermark"
	Dim oWatermarkBorderDefName As String = "Border With Watermark"
	'switch all sheet borders to one WITH Watermark
	ChangeAllBorders(oDDoc, oWatermarkBorderDefName)
	'export to PDF
	'<<<< EDIT PDF PATH & FILE NAME TO SUIT YOUR NEEDS >>>>
	Dim oPDF_Folder As String = "C:\Temp\PDFs\"
	Dim oPDF_FileName As String = System.IO.Path.GetFileNameWithoutExtension(oDDoc.FullFileName)
	Dim oPDF_FullFileName As String = oPDF_Folder & oPDF_FileName & ".pdf"
	ExportToPDF(oDDoc, oPDF_FullFileName)
	'now change all sheet borders back to their original borders
	ChangeAllBorders(oDDoc, oStandardBorderDefName)
	MsgBox("Done switching Borders & Exporting to PDF.",,"")
End Sub

Sub ChangeAllBorders(oDrawDoc As DrawingDocument, oBorderDefName As String)
	Dim oBorderDef As BorderDefinition = Nothing
	Try
		oBorderDef = oDrawDoc.BorderDefinitions.Item(oBorderDefName)
	Catch
		MsgBox("Could not find a BorderDefinition named '" & oBorderDefName & "'.", vbCritical, "")
		'Logger.Error("Could not find a BorderDefinition named '" & oBorderDefName & "'.")
		Exit Sub
	End Try
	'switch all sheet borders to one WITH Watermark
	Dim oASheet As Sheet = oDrawDoc.ActiveSheet
	For Each oSheet As Sheet In oDrawDoc.Sheets
		oSheet.Activate
		If oSheet.Border IsNot Nothing Then
			If oSheet.Border.Name <> oBorderDefName Then
				oSheet.Border.Delete
				oSheet.AddBorder(oBorderDef) 'option to input prompt strings
			End If
		Else 'oSheet.Border Is Nothing - could just do nothing here too
			oSheet.AddBorder(oBorderDef) 'option to input prompt strings
		End If
	Next
	oASheet.Activate
End Sub

Sub ExportToPDF(oDrawDoc As DrawingDocument, oNewFullFileName As String)
	'<<<< YOUR CODE FOR EXPORTING A DRAWING TO PDF HERE >>>>
End Sub

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes
Message 7 of 10

Jason.Rugg
Collaborator
Collaborator

@WCrihfield Thank you for your help, I will try this out later today or next week. Ultimately what I am trying to do is capture a snapshot of our drawing release process. Eventually I would like to have a single click button that once pressed will either swap out the border for a nearly identical border with "approved for fab" and some prompted entry text for signature, date, time, job # and rev. or just have the code place a stamp on the drawing with the same info. After that info is filled out the code would automatically print a hard copy and make a pdf saved next to the parent file (if we can get this far the next step would be to have that pdf actually saved in a sub folder in the parent file directory and checked into vault) Once the pdf file is created and saved it would revert the actual inventor drawing back to its original state without the "approved for fab" info on it and save and check in the file.

 

To complicate it a little more, when entering the "approved for fab" info, if a rev is entered that is anything other than a blank or a "0" it would put yet a different border or additional static stamp on the drawing that basically says its a revised drawing and previous revs (printed hard copies) need to be destroyed.

 

Is something like this doable? Any tools/code out there already that would accomplish this? To me this seems pretty complicated but I'm guessing it's really not. If you think you can help me out with this feel free to send me a pm and maybe I can share some of my files and existing code with you. Thanks

0 Likes
Message 8 of 10

WCrihfield
Mentor
Mentor

I'm about to leave for the weekend, so no time to write more code right now.  The alternate border or stamp part sounds doable.  I'm thinking maybe a SketchedSymbol if you go the 'stamp' route, because those can contain prompted entries too.  And of course the PDF export part sounds OK.  But I have not used Vault yet, so I won't be able to help with coding that part of the plan yet.  (We have been talking about getting Vault for years,  and plans are in place, but still not implemented.  Corporate red tape, among other stuff.)  Have a good one.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes
Message 9 of 10

Jason.Rugg
Collaborator
Collaborator

@WCrihfield Sounds good and thank you, I am getting out of here too. I'm good with either an alternate border or a stamp. Only reason I would go with the border is because I can place the information consistently across multiple drawings where with a stamp the user would have to manually place the stamp on the drawing in a location that doesn't interfere with the actual drawing. If we can get it to do all of this with the exception of the vault stuff that would be great. Vault can be figured out later on.

0 Likes
Message 10 of 10

Jason.Rugg
Collaborator
Collaborator

@WCrihfield Been trying to work with the ilogic you provided a couple of weeks ago and I'm failing to make it work.

 

My codes below that I currently use to make pdf's and prints.

 

Here is my code currently for pdf's:

Sub Main
	
iProperties.Value("Custom", "PlotDate&Time") = Now.ToString()	
	
Dim oDrgDoc As DrawingDocument
oDrgDoc = ThisApplication.ActiveDocument

' Set reference to drawing print manager' DrawingPrintManager has more options than PrintManager' as it's specific to drawing document
Dim oDrgPrintMgr As DrawingPrintManager
oDrgPrintMgr = oDrgDoc.PrintManager
Dim pdfname = ThisDoc.FileName(False)
Dim filePath = ThisDoc.Path
' Set the printer name' comment this line to use default printer or assign another one
oDrgPrintMgr.Printer = "Microsoft Print To PDF"

'Set the paper size , scale and orientation
'oDrgPrintMgr.ScaleMode = PrintScaleModeEnum.kPrintCustomScale
oDrgPrintMgr.ScaleMode = PrintScaleModeEnum.kPrintBestFitScale
'oDrgPrintMgr.PaperSize = PaperSizeEnum.kPaperSizeLedger
oDrgPrintMgr.PaperSize = PaperSizeEnum.kPaperSize11x17
'oDrgPrintMgr.PaperSize = 14338
oDrgPrintMgr.PrintRange = PrintRangeEnum.kPrintAllSheets
oDrgPrintMgr.Orientation = kLandscapeOrientation
'oDrgPrintMgr.PaperSource = 2
oDrgPrintMgr.AllColorsAsBlack = False

Dim pdfFileName = Path.Combine(filePath, pdfname + ".pdf")
If Not CanSaveToFile(pdfFileName) Then
	MessageBox.Show("Folder or file is read only", "Save PDF")

	Dim oFileDlg As Inventor.FileDialog 
	Call ThisApplication.CreateFileDialog(oFileDlg)
	
	oFileDlg.FilterIndex = 1 

  	oFileDlg.DialogTitle = "Save file" 

  	'oFileDlg.InitialDirectory = 
  	oFileDlg.CancelError = False  
	
	oFileDlg.FileName = pdfname + ".pdf"
 	Call oFileDlg.ShowSave() 
	
	pdfFileName = oFileDlg.FileName
	If String.IsNullOrEmpty(pdfFileName) Then 
		Logger.Info("No file specified")
		Return
	End If
End If

oDrgDoc.SaveAs(pdfFileName, True) 	

End Sub

Function CanSaveToFile(fileName As String)
	Dim fileInfo As New FileInfo(fileName)
	If fileInfo.Exists Then
		If fileInfo.IsReadOnly Then
			Return False
		ElseIf FileIsLocked(fileInfo) Then
			' We can't write to it. It might be open in Adobe Acrobat Reader
			Return False
		End If
	End If
	
	' make sure we can write to the directory
	Dim folderName = Path.GetDirectoryName(fileName)
	Dim tempName = Path.Combine(folderName, System.Guid.NewGuid().ToString() + ".txt")
	Try
		File.WriteAllText(tempName, "test")
		File.Delete(tempName)
	Catch
		Return False
	End Try
		
	Return True		
End Function

' from https://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use
Function FileIsLocked(fileInfo As FileInfo) As Boolean

    Dim stream As FileStream = Nothing

    Try
        stream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.None)
    Catch ex As IOException
        'the file is unavailable because it is:
        'still being written To
        'or being processed By another thread
        'or does Not exist (has already been processed)
        Return True
    Finally
        If (stream IsNot Nothing) Then
            stream.Close()
		End If
	End Try
		
    Return False
End Function



And here is my code currently for printing:

'check for custom iprops and add them if not found
Dim propertyName1 As String = "CurrentUser"
Dim propertyName2 As String = "PlotDate&Time"

customPropertySet = ThisDoc.Document.PropertySets.Item _
("Inventor User Defined Properties")

Try
          prop = customPropertySet.Item(propertyName1)
          prop = customPropertySet.Item(propertyName2)
Catch
      ' Assume error means not found
            customPropertySet.Add("", propertyName1)
          customPropertySet.Add("", propertyName2)
End Try

'output the custom iproperties and update the file
RuleParametersOutput()
InventorVb.DocumentUpdate()


'Plot Stamp
'Applies current filename & path, Date & time, and current user stamp to edge of border to be printed with the drawing
'[
iProperties.Value("Custom", "PlotDate&Time") = Now & " " & Time
iProperties.Value("Custom", "CurrentUser") = System.Security.Principal.WindowsIdentity.GetCurrent.Name

InventorVb.DocumentUpdate()

'Dim oCtrlDef As ControlDefinition
'oCtrlDef = ThisApplication.CommandManager.ControlDefinitions.Item("AppFilePrintCmd")
'oCtrlDef.Execute
']

'Print Setup
'[
Dim oDrgDoc As DrawingDocument
oDrgDoc = ThisApplication.ActiveDocument

' Set reference to drawing print manager' DrawingPrintManager has more options than PrintManager' as it's specific to drawing document
Dim oDrgPrintMgr As DrawingPrintManager
oDrgPrintMgr = oDrgDoc.PrintManager
' Set the printer name' comment this line to use default printer or assign another one
'oDrgPrintMgr.Printer = "\\kcidc2012\EngineeringSharp_Ledger"
'oDrgPrintMgr.Printer = "EngineeringSharp_Ledger"
'oDrgPrintMgr.Printer = "\\kcidc2012\EngineeringSharp_Ledger_Color"
oDrgPrintMgr.Printer = "\\kcipdc2019\Engineering_Ledger_Color"

'Set the paper size , scale and orientation
oDrgPrintMgr.ScaleMode = kCustomScale
oDrgPrintMgr.ScaleMode = PrintScaleModeEnum.kPrintBestFitScale
'oDrgPrintMgr.PaperSize = PaperSizeEnum.kPaperSizeLedger
'oDrgPrintMgr.PaperSize = PaperSizeEnum.14338
'oDrgPrintMgr.PaperSize = PaperSizeLedger
oDrgPrintMgr.PrintRange = kPrintCurrentSheet
oDrgPrintMgr.Orientation = kLandscapeOrientation
oDrgPrintMgr.PaperSource = 2
oDrgPrintMgr.AllColorsAsBlack = False
oDrgPrintMgr.SubmitPrint
']




 

 

0 Likes