Need help modifying this lisp code to automatically know how many pages are in a pdf and size them appropriately when inserted

Need help modifying this lisp code to automatically know how many pages are in a pdf and size them appropriately when inserted

fabi_rm94
Enthusiast Enthusiast
1,688 Views
22 Replies
Message 1 of 23

Need help modifying this lisp code to automatically know how many pages are in a pdf and size them appropriately when inserted

fabi_rm94
Enthusiast
Enthusiast

Hello everyone,

 

Have a question about the best way to modify this code to automatically know how many pages are in a pdf and size them appropriately within the paper space page layout. The code currently ask in its second step how many pages the user wants to bring in from the selected pdf. I want to bypass that 2nd step and have the code be able to know how many pages are in the pdf document and automatically place them and scale them on the page. 

 

I want to size the pdf pages/documents as follows:

     -  If the file has 1 sheet and is in portrait orientation, then the insertion location should be "4.5, 1.375" and scale of "0.75".

     - If the file has 1 sheet and is in landscape orientation, then the insertion location should be "0.75, 1.375" and be a scale of "0.75".

     - If the file has 2 sheets, then the insertion locations should be "0.75, 1.375" for the 1st page and "7.5, 1.375" for the 2nd page, both with a scale of "0.75".

     - If the file has 3 sheets, then the insertion locations should be "0.75, 3.025" for the 1st page, "5.23, 3.025" for the 2nd page, and "9.71, 3.025" for the 3rd page, all with a scale of "0.48".

     - If the file has 4 sheets, then the insertion locations should be "0.37629, 3.3" for the 1st page, "3.85812, 3.3" for the 2nd page, "7.33995, 3.3" for the 3rd page, and "10.8218, 3.3" for the 4th page.

 

 

BUPSUP(defun c:BUPSUP ( / )
	(c:BUPSUP)
)

(defun c:BUPSUP 
	( 
		/
		; Functions
			MN:ListBox _PDFPageCount findEmptySlot IncrementSheet ClearSheet
		;Variables
			dir lst mfr specs inspts pt scl pages page_lst cur_layout
	)
	
	(cb:writetotext "networks" "SPCI")
	
	(vl-load-com)
	
	(defun MN:ListBox ( title lst bit / *error* dch des tmp res )

		(defun *error* ( msg )
			(if (< 0 dch)
				(unload_dialog dch)
			)
			(if (= 'file (type des))
				(close des)
			)
			(if (and (= 'str (type tmp)) (setq tmp (findfile tmp)))
				(vl-file-delete tmp)
			)
			(if (not (wcmatch (strcase msg t) "*break,*cancel*,*exit*"))
				(princ (strcat "\nError: " msg))
			)
			(princ)
		)

		(cond
			(
				(not
					(and
						(setq tmp (vl-filename-mktemp nil nil ".dcl"))
						(setq des (open tmp "w"))
						(write-line
							(strcat
								"listbox : dialog
								{
									label = \"" title "\";
									spacer;
									: list_box
									{
										key = \"list\";
										multiple_select = " (if (null bit) "false" "true")";
									}
									width = 50;
									fixed_width = true;
									spacer;
									ok_cancel;
								}"
							)
							des
						)
						(not (close des))
						(< 0 (setq dch (load_dialog tmp)))
						(new_dialog "listbox" dch)
					)
				)
				(prompt "\nError loading list box.")
			)
			( 1
				(start_list "list")
				(foreach item lst (add_list item))
				(end_list)
				(setq res (set_tile "list" "0"))
				(action_tile "list" "(setq res $value)")
				(setq res
					(if (= 1 (start_dialog))
						(mapcar '(lambda ( x ) (nth x lst)) (read (strcat "(" res ")")))
					)
				)
			)
		)
		(if (< 0 dch)
			(setq dch (unload_dialog dch))
		)
		(if (and (= 'str (type tmp)) (setq tmp (findfile tmp)))
			(vl-file-delete tmp)
		)
		(if (not (null res))
			res
			nil
		)
	)
	
	(defun _PDFPageCount ( filename / fob fso mat reg res str )
		(if
			(and
				(setq filename (findfile filename))
				(eq ".PDF" (strcase (vl-filename-extension filename)))
			)
			(vl-catch-all-apply
				(function
					(lambda ( / _ReadAsTextFile _CountPage )
						(defun _ReadAsTextFile ( fso fn / fob str res )
							(setq
								fob (vlax-invoke fso 'getfile fn)
								str (vlax-invoke fso 'opentextfile fn 1 0)
								res (vlax-invoke str 'read (vlax-get fob 'size))
							)
							(vlax-invoke str 'close)
							(vlax-release-object str)
							(vlax-release-object fob)
							res
						)
						(defun _CountPage ( rgx str / mat pag )
							(vlax-put-property rgx 'pattern "/Type\\s*/Page[^s]")
							(vlax-put-property rgx 'ignorecase actrue)
							(vlax-put-property rgx 'global actrue)
							(setq
								mat (vlax-invoke rgx 'execute str)
								pag (vlax-get mat 'count)
							)
							(vlax-release-object mat)
							(if (zerop pag) 1 pag)             
						)
						(setq
							fso (vlax-create-object "Scripting.FileSystemObject")
							reg (vlax-create-object "VBScript.RegExp")
							str (_ReadAsTextFile fso filename)
							res (_CountPage reg str)
						)
					)
				)
			)
		)
		(foreach obj (list str fob mat fso reg)
			(vl-catch-all-apply 'vlax-release-object (list obj))
		)
		res
	)
	;; Translation by Lee Mac of the VBScript code by Chanh Ong
	;; found at http://docs.ongetc.com/?q=content/pdf-pages-counting-using-vb-script
	;;
	;; Call with fully qualified filename of PDF file:
	;; (_PDFPageCount "C:\\Folder\\Filename.pdf")
	;;
	;; Returns integer describing number of pages in specified PDF file
	
	
	(defun findEmptySlot ( lst / i ent nums )
		;; CONVERT LST "1.009,2.869,3.14" -> (LIST 1.009 2.869 3.14)
		(setq i 0)
		(cond
			((eq 'STR (type (nth i lst)))
				(setq nums (mapcar '(lambda (x y) (cons (atof (substr x 1 (vl-string-search "," x))) (atof (substr y (+ (vl-string-search "," y) 2))))) lst lst))
				(while (and (setq ent (nentselp "" (list (car (nth i nums)) (cdr (nth i nums))))) (/= i (1- (length lst))))
					;(vl-remove-if-not '(lambda (x) (wcmatch x "*R-*")) (layoutlist))
					(setq i (1+ i))
				)
				(if (null ent)
					(nth i lst)
				)
			)
		)
	)
	
	
	(defun ClearSheet ( ss / ind ent )
		(repeat (setq ind (sslength ss))
			(setq
				ind (1- ind)
				ent (ssname ss ind)
			)
			(entdel ent)
		)
		(princ)
	)
	; [SS] SELECTION SET 
	; CLEARS OUT ALL ENTITIES PASSED AS SELECTION SET [SS]
	
	
	(defun IncrementSheet ( sht / sht+ )
		(setq sht+
			(strcat
				(substr sht 1 (1+ (vl-string-search "-" sht)))
				(rtos (1+ (atoi (substr sht (+ (vl-string-search "-" sht) 2)))) 2 0)
			)
		)
	)
	
	
	;;; MAIN ;;;
	(setq dir "C:\\_Vault\\ATC\\DAS\\_DAS Library\\BUP Supplementals")
	(if (not (vl-file-directory-p dir))
		(princ (strcat "Directory: " dir "\nNot found.\nPlease download/'GET' this location from Vault."))
		(progn
			(setq lst (vl-remove-if '(lambda (x) (and (member x (list "." ".." "_V")))) (vl-directory-files dir nil -1)))
			(if
				(and
					(setq mfr (car (MN:ListBox "Select Generator Manufacturer:" lst nil)))
					(setq specs (MN:ListBox "Select Generator Spec Sheet(s):" (vl-directory-files (strcat dir "\\" mfr) "*.pdf*" 1) 1))
				)
				(progn
					(setq
						inspts (list
									"0.60475,1.38142"
									"7.42514,1.38142"
								)
						scl "0.77272727"
					)
					(if (vl-catch-all-error-p (vl-catch-all-apply 'setvar (list "CTAB" "R-601")))
						(princ "\nError.\nLayout tab 'R-601' does not exist.")
						(foreach spec specs
							;(command-s "PDFATTACH" (strcat dir "\\" mfr "\\" spec))
							(setq pages (_PDFPageCount (strcat dir "\\" mfr "\\" spec)))
							(setq page_lst nil)
							(repeat pages
								(setq page_lst (cons (rtos pages 2 0) page_lst))
								(setq pages (1- pages))
							)
							
							(setq page_lst (MN:Listbox (strcat "Select " spec " sheet(s):") page_lst 1))
							
							(foreach p page_lst
								(setq cur_layout (getvar "CTAB"))
								(while
									(not
										(cond
											((setq pt (findEmptySlot inspts))
												; insertion point or nil
												T
											)
											((vl-catch-all-error-p (vl-catch-all-apply 'setvar (list "CTAB" (setq cur_layout (IncrementSheet (getvar "CTAB"))))))
												; T or nil
												(command "_.LAYOUT" "C" (getvar "CTAB") cur_layout)
												(setvar "CTAB" cur_layout)
												(ClearSheet (ssget "C" '(0.60475 9.88142) '(13.9933 1.38142)))
												(setq pt (findEmptySlot inspts))
											)
										)
									)
								)
								(command "-PDFATTACH" (strcat dir "\\" mfr "\\" spec) p pt scl "0.0" nil)
								(setq pt nil)
							)
						)
					)
				)
				(princ "\nFunction canceled")
			)
		)
	)
	(princ)
)


;;;---------------------------------------------------------------------------------------------
; ...
; ...
;;;---------------------------------------------------------------------------------------------

 

 

I've attached the lisp code and the template to help with context. Feel free to modify the setq dir "C:\\_Vault\\ATC\\DAS\\_DAS Library\\BUP Supplementals" to any location with whatever pdfs you want to use to test out the code. 

 

Appreciate any help. 

0 Likes
Accepted solutions (2)
1,689 Views
22 Replies
Replies (22)
Message 21 of 23

paullimapa
Mentor
Mentor
Accepted solution

I found the error of my ways...I forgot one setq pdfname statement and messed it up.

This section now should work. I also attached the modified lisp file. I had to include LM: functions in order for me to run testing. You can take them all out or leave them in.

                   (foreach attribute (vlax-invoke obj 'getattributes) ; cycle through all attributes
                     (setq attribute_tag (strcase (vla-get-tagString attribute)))
                     (cond
                      ((wcmatch attribute_tag tagname) ; when found matching tag
;
; Following section removes numbers from begginning of PDF file names
;
;                       For example: "285 TANK SPEC.pdf"
                        (setq pdfname (vl-filename-base spec)) ; get pdf name with no extension
;                       Returns: "285 TANK SPEC"
                        (setq namechk(atoi pdfname)) ; if name does not begin with # then returns 0 otherwise in this case returns: 285
                        (if (not (zerop namechk)) ; do the following when name begins with #
                         (progn
                          (setq namelength (strlen (itoa namechk))) ; find out numbers have how many characters in this case returns: 3
                          (setq pdfname (substr pdfname (+ namelength 2))) ; assumes there's a space following #s gets rest of name in this case returns: TANK SPEC 
                         )
                        )
                        (vla-put-textString attribute pdfname) ; put pdf name as string value
;
; comment out this line (vla-put-textString attribute (vl-filename-base spec)) ; put entire pdf name with no extension as string value
;
                      ) 
                      ((wcmatch attribute_tag tagscale) ; when found matching tag
                       (vla-put-textString attribute "") ; put empty string value
                      ) 
                     ) ; cond
                    ) ; foreach

 


Paul Li
IT Specialist
@The Office
Apps & Publications | Video Demos
0 Likes
Message 22 of 23

fabi_rm94
Enthusiast
Enthusiast

You're the best!!! Learned so much from you!

0 Likes
Message 23 of 23

paullimapa
Mentor
Mentor

Once again glad to have helped…cheers!!!


Paul Li
IT Specialist
@The Office
Apps & Publications | Video Demos
0 Likes