PDFnUP

ポスター印刷(左右分割)時のページ順の決定方法

20240907052451_1412x1040

左右見開き状態で2upされているPDFのページを左右に分割印刷する場合
OSや用紙設定(余白値)にプリンタにも依存があるかも?しれませんが
私の環境macOS14+FF系のプリンタ
だと、以下のような事が言えます
『文字が読める向きの見た目の上下』と
『PDFページの構造上の天地方向』は
『PDFページの回転値で別』

20240908013836_1476x1496

ページの回転

最初に切り取られるページと紐づいている
使用したサンプルPDF

ダウンロード - PDFの回転確認用.zip


サンプルJavascriptファイル

ダウンロード - ワンライナー.js.txt




1:対象のPDFを開く
2:Javascriptコンソール(デバッガー)を開いてコンソールモードに
3:スクリプトをペーストして
4:コマンドキーを押しならがリターンキー

1:対象のPDFを開く
2:Javascriptコンソール(デバッガー)を開いてコンソールモードに
20240908021129_1170x1080
3:スクリプトをペーストして

サンプルコード

サンプルソース(参考)
行番号ソース
001var numAllPage = this.numPages;console.println("\n");for (var nPage = 0; nPage < numAllPage; nPage++) {var numPageRotation = this.getPageRotation(nPage);var strPrintPageNo = (nPage + 1);if (numPageRotation == 0) {console.println("現在のページ番号: " + strPrintPageNo + "\t回転: " + numPageRotation + "\t天地/上下");} else if (numPageRotation == 90) {console.println("現在のページ番号: " + strPrintPageNo + "\t回転: " + numPageRotation + "\t天地/右左");} else if (numPageRotation == 180) {console.println("現在のページ番号: " + strPrintPageNo + "\t回転: " + numPageRotation + "\t天地/下上");} else if (numPageRotation == 270) {console.println("現在のページ番号: " + strPrintPageNo + "\t回転: " + numPageRotation + "\t天地/左右");} else {console.println("エラーPDFのページ回転構造に問題があります");console.println("現在のページ番号: " + strPrintPageNo + "\t回転: " + numPageRotation);}}
AppleScriptで生成しました
20240908021143_1170x1080
4:コマンドキーを押しならがリターンキー
20240908021147_1170x1080

|

[applescript]A4縦型PDF文書をA4横型PDFに2IN1 2upで印刷PDFファイルにする(途中)


AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#! /usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#  ページ間にシャドウが入ってしまうので途中で断念
005# com.cocolog-nifty.quicktimer.icefloe
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "UniformTypeIdentifiers"
010use framework "AppKit"
011use framework "PDFKit"
012use scripting additions
013
014property refMe : a reference to current application
015#A4 PTサイズ 小数点以下2位
016property ocidA4Rect : {{0.0, 0.0}, {595.28, 841.89}}
017property ocidA4Size : {width:595.28, height:841.89}
018#
019property ocidA4HRect : {{0.0, 0.0}, {841.89, 595.28}}
020property ocidA4HSize : {width:841.89, height:595.28}
021#
022property ocidA4LRect : {{0.0, 0.0}, {595.28, 841.89}}
023property ocidA4RRect : {{0.0, 297.64}, {595.28, 841.89}}
024
025set appFileManager to refMe's NSFileManager's defaultManager()
026
027################
028#入力 ファイル
029set strName to (name of current application) as text
030if strName is "osascript" then
031  tell application "Finder" to activate
032else
033  tell current application to activate
034end if
035#デスクトップ
036set appFileManager to refMe's NSFileManager's defaultManager()
037set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
038set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
039set aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias
040#ダイアログ
041set listUTI to {"com.adobe.pdf"}
042set strMes to ("PDFファイルを選んでください") as text
043set strPrompt to ("PDFファイルを選んでください") as text
044try
045  set aliasFilePath to (choose file strMes with prompt strPrompt default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
046on error
047  log "エラーしました"
048  return "エラーしました"
049end try
050#入力ファイルパスURL
051set strFilePath to (POSIX path of aliasFilePath) as text
052set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
053set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
054set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
055#ファイル名
056set ocidFileName to ocidFilePathURL's lastPathComponent()
057set ocidBaseFileName to ocidFileName's stringByDeletingPathExtension()
058
059################
060#出力 デスクトップ
061set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
062set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
063#出力ファイル名
064set strMergeFileName to ("A4_" & ocidBaseFileName) as text
065#出力ファイルパスURL
066set ocidBaseMergeFilePathURL to (ocidDesktopDirPathURL's URLByAppendingPathComponent:(strMergeFileName) isDirectory:(false))
067set ocidMergeFilePathURL to (ocidBaseMergeFilePathURL's URLByAppendingPathExtension:("pdf"))
068#出力するPDF書類
069set ocidMergeDoc to refMe's PDFDocument's alloc()'s init()
070
071################
072#入力:PDFDocument
073set ocidActivDoc to refMe's PDFDocument's alloc()'s initWithURL:(ocidFilePathURL)
074#ページ数
075set numCntPage to ocidActivDoc's pageCount()
076#奇数ページの場合最後のページにブランクページを挿入して偶数にする
077set numCntPageHarf to (numCntPage / 2) as number
078set numCntHarfInt to numCntPageHarf as integer
079#奇数なら
080if (numCntHarfInt - numCntPageHarf) > 0 then
081  #最後のページを取り出して
082  set ocidLastPage to ocidActivDoc's pageAtIndex:(numCntPage - 1)
083  #サイズを取得
084  set ocidPageBounds to ocidLastPage's boundsForBox:(refMe's kPDFDisplayBoxCropBox)
085  #取得したサイズでブランクページを作成
086  set ocidBlankPage to refMe's PDFPage's alloc()'s init()
087  ocidBlankPage's setBounds:(ocidPageBounds) forBox:(refMe's kPDFDisplayBoxMediaBox)
088  ocidBlankPage's setBounds:(ocidPageBounds) forBox:(refMe's kPDFDisplayBoxCropBox)
089  #最後にブランクページを挿入
090  ocidActivDoc's insertPage:(ocidBlankPage) atIndex:(numCntPage)
091  #ページ数が1ページ増える
092  set numCntPage to (numCntPage + 1) as integer
093end if
094#読み込みPDFのページ数レンジ
095set ocidPageRange to refMe's NSRange's NSMakeRange(0, (numCntPage - 1))
096
097
098################
099#テンポラリー
100#中間ファイルを保存する場合利用
101(*
102set ocidTempDirURL to appFileManager's temporaryDirectory()
103set ocidUUID to refMe's NSUUID's alloc()'s init()
104set ocidUUIDString to ocidUUID's UUIDString
105set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:true
106set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
107ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
108set listDone to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference)
109if (item 2 of listDone) ≠ (missing value) then
110  set strErrorNO to (item 2 of listDone)'s code() as text
111  set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
112  refMe's NSLog("■:" & strErrorNO & strErrorMes)
113  return "エラーしました" & strErrorNO & strErrorMes
114end if
115*)
116
117
118################
119#PDFView
120set ocidPageView to refMe's PDFView's alloc()'s initWithFrame:(ocidA4HRect)
121ocidPageView's setDocument:(ocidActivDoc)
122#set ocidPDFview to ocidPageView's documentView()
123
124################
125#ページの数だけ繰り返す
126set numCntMargPageNo to 0 as integer
127repeat with itemNo from 1 to (numCntPage) by 2
128  # set strSaveFileName to (itemNo & "_" & ocidBaseFileName) as text
129  # set ocidBaseSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName) isDirectory:(false))
130  # set ocidSaveFilePathURL to (ocidBaseSaveFilePathURL's URLByAppendingPathExtension:("pdf"))
131  ################
132  #PDFView
133  set ocidActivPage to (ocidActivDoc's pageAtIndex:(itemNo - 1))
134  (ocidPageView's goToPage:(ocidActivPage))
135  (ocidPageView's enablePageShadows:(false))
136  #
137  set ocidBackgroundColor to refMe's NSColor's clearColor()
138  (ocidPageView's setBackgroundColor:(ocidBackgroundColor))
139  (ocidPageView's setOpaque:(true))
140  #
141  set ocidEdgeInsets to refMe's NSEdgeInsets's NSEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
142  (ocidPageView's setAdditionalSafeAreaInsets:(ocidEdgeInsets))
143  # (ocidPageView's setAdditionalSafeAreaInsets:(refMe's NSEdgeInsetsZero))
144  #表紙の有無
145  (ocidPageView's setDisplaysAsBook:(false))
146  (ocidPageView's setInterpolationQuality:(refMe's kPDFInterpolationQualityHigh))
147  (ocidPageView's setDisplaysPageBreaks:(false))
148  (ocidPageView's setPageBreakMargins:(ocidEdgeInsets))
149  # (ocidPageView's setPageBreakMargins:(refMe's NSEdgeInsetsZero))
150  (ocidPageView's setDisplayDirection:(refMe's kPDFDisplayDirectionHorizontal))
151  #(ocidPageView's setDisplayBox:(refMe's kPDFDisplayBoxTrimBox))
152  (ocidPageView's setDisplayBox:(refMe's kPDFDisplayBoxCropBox))
153  #
154  (ocidPageView's setDisplayMode:(refMe's kPDFDisplayTwoUpContinuous))
155  #右開きの場合はtrue
156  (ocidPageView's setDisplaysRTL:(true))
157  (ocidPageView's setAutoresizingMask:(refMe's NSViewNotSizable))
158  # (ocidPageView's setAutoresizingMask:(18))
159  (ocidPageView's setAutoScales:(true))
160  (ocidPageView's setMaxScaleFactor:(0.71))
161  (ocidPageView's setMinScaleFactor:(0.70714))
162  log (ocidPageView's scaleFactorForSizeToFit()) as number
163  #   (ocidPageView's setScaleFactor:(0.49))
164  #
165  (ocidPageView's setClipsToBounds:(false))
166  
167  (ocidPageView's setAutoresizesSubviews:(true))
168  
169  #
170  set ocidShadow to refMe's NSShadow's alloc()'s init()
171  set ocidShadowColor to refMe's NSColor's clearColor()
172  (ocidShadow's setShadowColor:(ocidShadowColor))
173  (ocidPageView's setShadow:(ocidShadow))
174  (ocidPageView's setAlphaValue:(0.0))
175  #
176  ocidPageView's layoutDocumentView()
177  
178  #スクロールを表示させない
179  set ocidSubViewArray to ocidPageView's subviews()
180  set appScrollView to ocidSubViewArray's firstObject()
181  #
182  set ocidEdgeInsets to refMe's NSEdgeInsets's NSEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
183  (appScrollView's setScrollerInsets:(ocidEdgeInsets))
184  (appScrollView's setClipsToBounds:(true))
185  #
186  (appScrollView's setHasVerticalScroller:(false))
187  (appScrollView's setHasHorizontalScroller:(false))
188  #
189  (appScrollView's setHasVerticalRuler:(false))
190  (appScrollView's setHasHorizontalRuler:(false))
191  (appScrollView's setDrawsBackground:(false))
192  (appScrollView's setAutohidesScrollers:(true))
193  (appScrollView's setScrollerStyle:(refMe's NSScrollerStyleOverlay))
194  #
195  (ocidPageView's setWantsLayer:(true))
196  set ocidLay to ocidPageView's layer()
197  (ocidLay's setShadowOpacity:(0.0))
198  
199  ################
200  #印刷
201  #戻り値
202  set ocidResponse to doPrint(ocidPageView)
203  #失敗時
204  if ocidResponse is false then
205    return "印刷失敗"
206  else
207    #成功の場合は戻り値がPDFページデータ
208    set ocidPrintPage to ocidResponse
209  end if
210  #マージ用のPDFに戻り値のページデータを入れていく
211  (ocidMergeDoc's insertPage:(ocidPrintPage) atIndex:(numCntMargPageNo))
212  set numCntMargPageNo to (numCntMargPageNo + 1) as integer
213end repeat
214##マージしたPDFを保存する
215set boolDone to ocidMergeDoc's writeToURL:ocidMergeFilePathURL
216
217
218to doPrint(argPageView)
219  ################
220  #NSPrint
221  set ocidPrinterInfoDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
222  # ocidPrinterInfoDict's setObject:(refMe's NSPrintSaveJob) forKey:(refMe's NSPrintJobDisposition)
223  #ocidPrinterInfoDict's setObject:(argSaveFilePathURL) forKey:(refMe's NSPrintJobSavingURL)
224  ocidPrinterInfoDict's setObject:(true) forKey:(refMe's NSPrintAllPages)
225  ocidPrinterInfoDict's setObject:(1) forKey:(refMe's NSPrintCopies)
226  ocidPrinterInfoDict's setObject:(false) forKey:(refMe's NSPrintHeaderAndFooter)
227  #
228  ocidPrinterInfoDict's setObject:(0.0) forKey:(refMe's NSPrintLeftMargin)
229  ocidPrinterInfoDict's setObject:(0.0) forKey:(refMe's NSPrintRightMargin)
230  ocidPrinterInfoDict's setObject:(0.0) forKey:(refMe's NSPrintTopMargin)
231  ocidPrinterInfoDict's setObject:(0.0) forKey:(refMe's NSPrintBottomMargin)
232  #set appPrinterInfo to refMe's NSPrintInfo's sharedPrintInfo()
233  set appPrinterInfo to refMe's NSPrintInfo's alloc()'s initWithDictionary:(ocidPrinterInfoDict)
234  #DictにAttributeKeyで追加していく方法
235  #set ocidPrinterInfoDict to appPrinterInfo's dictionary()
236  
237  #setを使って簡易に設定していく方法
238  appPrinterInfo's setPaperName:("A4")
239  appPrinterInfo's setPaperSize:(ocidA4HSize)
240  appPrinterInfo's setOrientation:(refMe's NSPaperOrientationLandscape)
241  #   appPrinterInfo's setOrientation:(refMe's NSPaperOrientationPortrait)
242  #
243  appPrinterInfo's setHorizontallyCentered:(true)
244  appPrinterInfo's setVerticallyCentered:(true)
245  appPrinterInfo's setHorizontalPagination:(refMe's NSPrintingPaginationModeFit)
246  appPrinterInfo's setVerticalPagination:(refMe's NSPrintingPaginationModeFit)
247  
248  ################
249  #NSPrintOperation
250  #URLにファイルとして印刷する場合
251  # set appPrintOperation to refMe's NSPrintOperation's printOperationWithView:(argPageView) printInfo:(appPrinterInfo)
252  #パスにファイルとして印刷する場合
253  # set appPrintOperation to refMe's NSPrintOperation's PDFOperationWithView:(argPageView) insideRect:(ocidA4HRect) toPath:(ocidSaveFilePath) printInfo:(appPrinterInfo)
254  #データに印刷
255  set ocidPrintData to refMe's NSMutableData's alloc()'s initWithCapacity:(0)
256  set appPrintOperation to refMe's NSPrintOperation's PDFOperationWithView:(argPageView) insideRect:(ocidA4HRect) toData:(ocidPrintData) printInfo:(appPrinterInfo)
257  #
258  appPrintOperation's setShowsPrintPanel:(false)
259  appPrintOperation's setShowsProgressPanel:(false)
260  appPrintOperation's setPageOrder:(refMe's NSAscendingPageOrder)
261  #印刷
262  set boolDone to appPrintOperation's runOperation()
263  #
264  if boolDone is false then
265    log "印刷が失敗しました"
266    return false
267  end if
268  #印刷したデータからPDFを生成して
269  set ocidPrintDoc to refMe's PDFDocument's alloc()'s initWithData:(ocidPrintData)
270  #1ページ目を取得する
271  set ocidPrintPage to ocidPrintDoc's pageAtIndex:(0)
272  #ページデータを戻す
273  return ocidPrintPage
274  
275end doPrint
AppleScriptで生成しました

|

[swift]A4縦型PDF文書をA4横型PDFに2IN1 2upで印刷PDFファイルにする(途中)


サンプルコード

サンプルソース(参考)
行番号ソース
001#!/usr/bin/env swift
002// 各ページ間にドロップシャドウが出てしますう
003//--+----1----+----2----+-----3----+----4----+----5----+----6----+----7
004import Foundation
005import AppKit
006import PDFKit
007import Cocoa
008
009let rectA4H: NSRect = NSRect(x: 0, y: 0, width: 841.89, height: 595.28)
010let sizeA4H: NSSize = NSSize(width:841.89, height:595.28)
011let insetsZero: NSEdgeInsets = NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
012
013
014let appFileManager: FileManager = FileManager.default
015let urlDesktop: URL = appFileManager.urls(for: .desktopDirectory, in: .userDomainMask).first!
016//読み込むPDF A4サイズの縦型PDF 2ページ
017let urlReadFile: URL = urlDesktop.appendingPathComponent("A4P.pdf")
018//保存先PDF
019let urlSaveFile: URL = urlDesktop.appendingPathComponent("Save.pdf")
020//PDF読み込み
021guard let pdfDocument: PDFDocument = PDFDocument(url: urlReadFile) else {
022print("PDFの読み込みに失敗しました")
023exit(0)}
024
025// PDFViewを設定
026let pdfView: PDFView = PDFView(frame: rectA4H)
027pdfView.document = pdfDocument
028
029if let setPdfPage: PDFPage = pdfDocument.page(at :0){
030pdfView.go(to: setPdfPage)
031}
032pdfView.displayMode = .twoUpContinuous
033pdfView.displayDirection = .vertical
034pdfView.displaysAsBook = false 
035pdfView.displaysRTL = true
036pdfView.autoScales = true
037pdfView.maxScaleFactor = 0.71
038pdfView.minScaleFactor = 0.70714
039pdfView.displayBox = .cropBox
040pdfView.displaysPageBreaks = false
041pdfView.pageBreakMargins = insetsZero
042pdfView.pageShadowsEnabled = false
043pdfView.autoresizesSubviews = false
044pdfView.autoresizingMask = [.width, .height, .minXMargin, .minYMargin]
045pdfView.translatesAutoresizingMaskIntoConstraints = true
046//レイヤー
047pdfView.wantsLayer = true
048if let caLayer: CALayer = pdfView.layer {
049  caLayer.shadowOpacity = 0 
050  caLayer.shadowOffset = CGSize(width: -5, height: -5)
051  caLayer.shadowRadius = 0 
052}
053//スクローラー
054if let scrollView: NSScrollView = pdfView.subviews.first(where: { $0 is NSScrollView }) as? NSScrollView {
055scrollView.hasHorizontalScroller = false
056scrollView.hasVerticalScroller = false
057scrollView.hasHorizontalRuler = false
058scrollView.hasVerticalRuler = false
059scrollView.rulersVisible = false
060scrollView.autohidesScrollers = true
061scrollView.borderType = .noBorder
062scrollView.drawsBackground = false
063scrollView.clipsToBounds = false
064scrollView.scrollerInsets = insetsZero
065scrollView.scrollerStyle = .overlay 
066scrollView.wantsLayer = true
067//スクローラーのレイヤー
068if let caScLayer: CALayer = pdfView.layer {
069  caScLayer.shadowOpacity = 0 
070  caScLayer.shadowOffset = CGSize(width: -5, height: -5)
071  caScLayer.shadowRadius = 0 
072}
073}
074//SUBVIEW
075for itemView: NSView in pdfView.subviews {
076  if let itemCaLayer: CALayer = itemView.layer {
077    itemCaLayer.shadowOpacity = 0
078    itemCaLayer.shadowOffset = CGSize.zero
079    itemCaLayer.shadowRadius = 0
080  }
081}
082
083
084//NSPrintInfo
085let printerInfoDictionary: NSMutableDictionary = NSMutableDictionary()
086printerInfoDictionary.setObject(true, forKey: NSPrintInfo.AttributeKey.allPages.rawValue as NSCopying)
087let printInfo: NSPrintInfo = NSPrintInfo(dictionary: printerInfoDictionary as! [NSPrintInfo.AttributeKey: Any])
088//let printInfo: NSPrintInfo = NSPrintInfo.shared
089printInfo.orientation = .portrait
090printInfo.horizontalPagination = .fit
091printInfo.verticalPagination = .fit
092printInfo.paperSize = sizeA4H
093printInfo.isHorizontallyCentered = true
094printInfo.isVerticallyCentered = true
095printInfo.leftMargin = 0.0
096printInfo.rightMargin = 0.0
097printInfo.topMargin = 0.0
098printInfo.bottomMargin = 0.0
099
100//NSPrintOperation
101let pdfOperation: NSPrintOperation = NSPrintOperation.pdfOperation(with: pdfView, inside: rectA4H, toPath: urlSaveFile.path, printInfo: printInfo)
102pdfOperation.showsPrintPanel = false
103pdfOperation.showsProgressPanel = false
104if pdfOperation.run() {
105    print("PDFが正常に保存されました")
106} else {
107    print("PDFの保存に失敗しました")
108}
109
110
AppleScriptで生成しました

|

[pypdf]PDF8UP

ダウンロード - pdfPDF8UP回転考慮.zip

|

[pypdf]PDF3UP

ダウンロード PDF3UP回転考慮.zip

|

[pypdf]単ページPDFを3in1 3upに集約する(回転は考慮しない 左から右へ)

ダウンロード - pdf3upl2r.zip


【スクリプトエディタで開く】|

#!/usr/bin/env python3
import sys
import math
from pypdf import PdfReader
from pypdf import PdfWriter
from pypdf import PageObject
from pypdf import Transformation
from pypdf.generic import RectangleObject

#########################################入力パスを受け取る
argGetData = sys.argv
strFilePath = str(argGetData[1])
#テスト用
# strFilePath = "/path/to/some/pdf/file.pdf"

strOutputPDFDocPath = strFilePath + ".3in1.pdf"
try:
  with open(strFilePath, 'rb') as objInputData:
#########################################ライター初期化
    objReader = PdfReader(objInputData)
    objWriter = PdfWriter()
#########################################ページ数調べる
    objAllPages = objReader.pages
    numAllPage = int(len(objAllPages))
    print(numAllPage)
#########################################奇数偶数判定使わないけど
    if numAllPage % 2 == 0:
      print("偶数")
    else:
      print("奇数")
    numRepeatTImes = math.ceil(numAllPage / 3 )
    print(numRepeatTImes)
#########################################ページ数➗2回数繰り返し
    numCntInPage = int(0)
    for numTimes in range(numRepeatTImes):
#########################################右側ページ
      objPageR = objReader.pages[numCntInPage]
      numWR = objPageR.mediabox.right
      numHR = objPageR.mediabox.top
      print("R :" , numWR , "x" , numHR)
#########################################センターページ
      if numCntInPage == (numAllPage - 1):
objPageC = PageObject.create_blank_page(width=numWR, height=numHR)
numWC = objPageR.mediabox.right
numHC = objPageR.mediabox.top
      else:
numCntInPage = numCntInPage + 1
objPageC = objReader.pages[numCntInPage]
numWC = objPageC.mediabox.right
numHC = objPageC.mediabox.top
print("C :" , numWC , "x" , numHC)
numCntInPage = numCntInPage + 1
#########################################左ページ
      if numCntInPage == numAllPage:
objPageL = PageObject.create_blank_page(width=numWR, height=numHR)
numWL = objPageR.mediabox.right
numHL = objPageR.mediabox.top
      else:
objPageL = objReader.pages[numCntInPage]
numWL = objPageL.mediabox.right
numHL = objPageL.mediabox.top
print("L :" , numWL , "x" , numHL)
numCntInPage = numCntInPage + 1
#########################################新規ページの高さは最大値
      if numHR >= numHL:
numNewH = numHR
      else:
numNewH = numHL
#########################################新規ページの幅
      numNewW = numWL + numWL + numWC
#########################################3Wサイズで新規ページ
      print("3W:" , numNewW , "x" , numNewH)
      objNewPage = PageObject.create_blank_page(None,numNewW,numNewH)
#########################################左側ページを新規ページに
      objOption = Transformation().translate(tx=(numWL + numWC))
      objPageL.add_transformation(objOption,True)
      objPageL.mediabox = RectangleObject((0,0,numNewW,numNewH))
      objPageL.cropbox = RectangleObject((0,0,numNewW,numNewH))
      objPageL.trimbox = RectangleObject((0,0,numNewW,numNewH))
      objPageL.bleedbox = RectangleObject((0,0,numNewW,numNewH))
      objPageL.artbox = RectangleObject((0,0,numNewW,numNewH))
      objNewPage.merge_page(objPageL,False)
#########################################中央ページを新規ページに
      objOption = Transformation().translate(tx=numWL)
      objPageC.add_transformation(objOption,True)
      objPageC.mediabox = RectangleObject((0,0,numNewW,numNewH))
      objPageC.cropbox = RectangleObject((0,0,numNewW,numNewH))
      objPageC.trimbox = RectangleObject((0,0,numNewW,numNewH))
      objPageC.bleedbox = RectangleObject((0,0,numNewW,numNewH))
      objPageC.artbox = RectangleObject((0,0,numNewW,numNewH))
      objNewPage.merge_page(objPageC,False)
#########################################右側ページのリサイズ
      objOption = Transformation().translate(tx=0)
      objPageR.add_transformation(objOption,True)
      objPageR.mediabox = RectangleObject((0,0,numNewW,numNewH))
      objPageR.cropbox = RectangleObject((0,0,numNewW,numNewH))
      objPageR.trimbox = RectangleObject((0,0,numNewW,numNewH))
      objPageR.bleedbox = RectangleObject((0,0,numNewW,numNewH))
      objPageR.artbox = RectangleObject((0,0,numNewW,numNewH))
      objNewPage.merge_page(objPageR,True)
#########################################新規ページのサイズ
      objNewPage.mediabox = RectangleObject((0,0,numNewW,numNewH))
      objNewPage.cropbox = RectangleObject((0,0,numNewW,numNewH))
      objNewPage.trimbox = RectangleObject((0,0,numNewW,numNewH))
      objNewPage.bleedbox = RectangleObject((0,0,numNewW,numNewH))
      objNewPage.artbox = RectangleObject((0,0,numNewW,numNewH))
      objWriter.add_page(objNewPage)
except FileNotFoundError:
  print("ファイルのオープンに失敗しました")
  sys.exit(0)
try:
#########################################
  with open(strOutputPDFDocPath, 'wb') as objOutPutData:
    objWriter.write(objOutPutData)
except FileNotFoundError:
    print("ファイルの保存に失敗しました")

sys.exit(0)



|

[pypdf]単ページPDFを3in1 3upに集約する(回転は考慮しない 右から左へ)

ダウンロード - pdf3upr2l.zip


【スクリプトエディタで開く】|

#!/usr/bin/env python3
import sys
import math
from pypdf import PdfReader
from pypdf import PdfWriter
from pypdf import PageObject
from pypdf import Transformation
from pypdf.generic import RectangleObject

#########################################入力パスを受け取る
argGetData = sys.argv
strFilePath = str(argGetData[1])
#テスト用
# strFilePath = "/path/to/pdf/some.pdf"

strOutputPDFDocPath = strFilePath + ".3in1.pdf"
try:
  with open(strFilePath, 'rb') as objInputData:
#########################################ライター初期化
    objReader = PdfReader(objInputData)
    objWriter = PdfWriter()
#########################################ページ数調べる
    objAllPages = objReader.pages
    numAllPage = int(len(objAllPages))
    print(numAllPage)
#########################################奇数偶数判定使わないけど
    if numAllPage % 2 == 0:
      print("偶数")
    else:
      print("奇数")
    numRepeatTImes = math.ceil(numAllPage / 3 )
    print(numRepeatTImes)
#########################################ページ数➗2回数繰り返し
    numCntInPage = int(0)
    for numTimes in range(numRepeatTImes):
#########################################右側ページ
      objPageR = objReader.pages[numCntInPage]
      numWR = objPageR.mediabox.right
      numHR = objPageR.mediabox.top
      print("R :" , numWR , "x" , numHR)
#########################################センターページ
      if numCntInPage == (numAllPage - 1):
objPageC = PageObject.create_blank_page(width=numWR, height=numHR)
numWC = objPageR.mediabox.right
numHC = objPageR.mediabox.top
      else:
numCntInPage = numCntInPage + 1
objPageC = objReader.pages[numCntInPage]
numWC = objPageC.mediabox.right
numHC = objPageC.mediabox.top
print("C :" , numWC , "x" , numHC)
numCntInPage = numCntInPage + 1
#########################################左ページ
      if numCntInPage == numAllPage:
objPageL = PageObject.create_blank_page(width=numWR, height=numHR)
numWL = objPageR.mediabox.right
numHL = objPageR.mediabox.top
      else:
objPageL = objReader.pages[numCntInPage]
numWL = objPageL.mediabox.right
numHL = objPageL.mediabox.top
print("L :" , numWL , "x" , numHL)
numCntInPage = numCntInPage + 1
#########################################新規ページの高さは最大値
      if numHR >= numHL:
numNewH = numHR
      else:
numNewH = numHL
#########################################新規ページの幅
      numNewW = numWL + numWL + numWC
#########################################3Wサイズで新規ページ
      print("3W:" , numNewW , "x" , numNewH)
      objNewPage = PageObject.create_blank_page(None,numNewW,numNewH)
#########################################左側ページを新規ページに
      objOption = Transformation().translate(tx=0)
      objPageL.add_transformation(objOption,True)
      objPageL.mediabox = RectangleObject((0,0,numNewW,numNewH))
      objPageL.cropbox = RectangleObject((0,0,numNewW,numNewH))
      objPageL.trimbox = RectangleObject((0,0,numNewW,numNewH))
      objPageL.bleedbox = RectangleObject((0,0,numNewW,numNewH))
      objPageL.artbox = RectangleObject((0,0,numNewW,numNewH))
      objNewPage.merge_page(objPageL,False)
#########################################中央ページを新規ページに
      objOption = Transformation().translate(tx=numWL)
      objPageC.add_transformation(objOption,True)
      objPageC.mediabox = RectangleObject((0,0,numNewW,numNewH))
      objPageC.cropbox = RectangleObject((0,0,numNewW,numNewH))
      objPageC.trimbox = RectangleObject((0,0,numNewW,numNewH))
      objPageC.bleedbox = RectangleObject((0,0,numNewW,numNewH))
      objPageC.artbox = RectangleObject((0,0,numNewW,numNewH))
      objNewPage.merge_page(objPageC,False)
#########################################右側ページのリサイズ
      objOption = Transformation().translate(tx=(numWL + numWC))
      objPageR.add_transformation(objOption,True)
      objPageR.mediabox = RectangleObject((0,0,numNewW,numNewH))
      objPageR.cropbox = RectangleObject((0,0,numNewW,numNewH))
      objPageR.trimbox = RectangleObject((0,0,numNewW,numNewH))
      objPageR.bleedbox = RectangleObject((0,0,numNewW,numNewH))
      objPageR.artbox = RectangleObject((0,0,numNewW,numNewH))
      objNewPage.merge_page(objPageR,True)
#########################################新規ページのサイズ
      objNewPage.mediabox = RectangleObject((0,0,numNewW,numNewH))
      objNewPage.cropbox = RectangleObject((0,0,numNewW,numNewH))
      objNewPage.trimbox = RectangleObject((0,0,numNewW,numNewH))
      objNewPage.bleedbox = RectangleObject((0,0,numNewW,numNewH))
      objNewPage.artbox = RectangleObject((0,0,numNewW,numNewH))
      objWriter.add_page(objNewPage)
except FileNotFoundError:
  print("ファイルのオープンに失敗しました")
  sys.exit(0)
try:
#########################################
  with open(strOutputPDFDocPath, 'wb') as objOutPutData:
    objWriter.write(objOutPutData)
except FileNotFoundError:
    print("ファイルの保存に失敗しました")

sys.exit(0)



|

[Foxit PDF Reader]集約PDF(Nup)を作成する

1:ファイル>>印刷
2:プロパティ
3:詳細画面
4:レイアウト
5:希望の面付け設定を選ぶ
6:PDFとして保存を選択
7:保存先とファイル名を選択(上書き注意)
8:保存(自動で閉じます)
9:プリントボタンを押す
10:指定先に集約PDFが作成されます



_20220819_22_16_21

_20220819_22_16_32

_20220819_22_16_38

_20220819_22_16_47

_20220819_22_16_56

_20220819_22_17_02
_20220819_22_17_36

_20220819_22_17_44

|

[Preview]PDFを集約(pdfNup3.py)

ダウンロード - pdfe99b86e7b484nuppreview.zip

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#Preview
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

use AppleScript version "2.8"
use framework "Foundation"
use scripting additions


####集約リスト
set listNup to {2, 4, 8, 9, 16, 18} as list

####ダイアログ
try
set objResponse to (choose from list listNup with title "選んでください" with prompt "1ページにNページ集約するか?" default items (item 1 of listNup) OK button name "OK" cancel button name "キャンセル" with multiple selections allowed without empty selection allowed)
on error
log "エラーしました"
return
end try
if objResponse is false then
return
end if
####戻り値確定
set numNup to (objResponse) as text

####集約向きリスト
set listDirs to {"LU", "LD", "RU", "RD"} as list
###ダイアログ
try
set objResponse to (choose from list listDirs with title "選んでください" with prompt "LU右下->右上\nLD右上->右下※\nRU左下->左上\nRD左上->左下※\n通常上から下です" default items (item 2 of listDirs) OK button name "OK" cancel button name "キャンセル" with multiple selections allowed without empty selection allowed)
on error
log "エラーしました"
return
end try
if objResponse is false then
return
end if
####戻り値確定
set strDirs to (objResponse) as text

####パス取得
tell application "Finder"
set aliasPathToMe to (container of (path to me)) as alias
set thePathToMe to (POSIX path of aliasPathToMe) as Unicode text
end tell
###コマンドへのパス
set strPyPath to ("" & thePathToMe & "bin/pdfNup.py")
####パスを取得
tell application "Preview"
tell window 1
properties
tell document 1
set strFilePath to path
set strFileName to name
end tell
end tell
end tell
###ファイル名とパス
set strDistName to doReplace(strFileName, ".pdf", "") as text
set strDistFileName to ("" & strDistName & "-" & numNup & "up.pdf") as text
####保存先パス
set aliasFilePath to (POSIX file strFilePath) as alias
set theFileDir to (POSIX path of aliasFilePath) as Unicode text
####ファイルの上書き警告と停止
tell application "Finder"
set aliasDistDir to (container of aliasFilePath) as alias
set boolFileExists to exists (file strDistFileName of folder aliasDistDir)
if boolFileExists is true then
display alert "エラー:ファイルがすでにあります移動してください" buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 10
return
end if
end tell
###パス確定
set strFilePath to POSIX path of aliasFilePath as text
####コマンド整形
set strCommandText to ("python3 \"" & strPyPath & "\" \"" & strFilePath & "\" " & numNup & " " & strDirs & "") as text
###ログ
log strCommandText
###コマンド実行
do shell script strCommandText

delay 3
###ファイルがあれば開く
tell application "Finder"
set aliasDistDir to (container of aliasFilePath) as alias
set boolFileExists to exists (file strDistFileName of folder aliasDistDir)
if boolFileExists is true then
set aliasDistFile to (file strDistFileName of folder aliasDistDir) as alias
tell application "Preview"
open aliasDistFile
end tell
end if
end tell



###置き換えのサブ
to doReplace(theText, orgStr, newStr)
set oldDelim to AppleScript's text item delimiters
set AppleScript's text item delimiters to orgStr
set tmpList to every text item of theText
set AppleScript's text item delimiters to newStr
set tmpStr to tmpList as text
set AppleScript's text item delimiters to oldDelim
return tmpStr
end doReplace


#!/usr/bin/env python3

# coding: utf-8

##from datetime import datetime

##import os

import sys

import urllib.parse

######

from pdfnup import generateNup

## 

##generateNup("test-legal-p.pdf", 8, verbose=True)



argGetData = sys.argv

strFilePath = str(argGetData[1])

numNup = int(argGetData[2])

strDirs = str(argGetData[3])



##generateNup(strFilePath, 2,  verbose=True)


##右ページ->左ページの読み順

##下から上に

##generateNup(strFilePath, 2, dirs="RU", verbose=True)

##上から下に

##generateNup(strFilePath, 2, dirs="RD", verbose=True)


##左ページ-->右ページ 

##下から上に

##generateNup(strFilePath, 4, dirs="LU", verbose=True)

##上から下に

##generateNup(strFilePath, 4, dirs="LD", verbose=True)


print(strFilePath)

print(numNup)

print(strDirs)


if strDirs == "RU":

    generateNup( strFilePath , numNup , dirs="RU", verbose=True)

elif strDirs == "RD":

    generateNup( strFilePath , numNup , dirs="RD", verbose=True)

elif strDirs == "LU":

    generateNup( strFilePath , numNup , dirs="LU", verbose=True)

elif strDirs == "LD":

    generateNup( strFilePath , numNup , dirs="LD", verbose=True)



##generateNup( strFilePath , numNup , dirs="'strDirs'" , verbose=True)


##

|

[python]PDFを集約(pdfNup3.py)

ダウンロード - pdfe99b86e7b484nup.zip



#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

####選んでもらうリスト
set listNup to {2, 4, 8, 9, 16, 18} as list
###ダイアログ
try
set objResponse to (choose from list listNup with title "選んでください" with prompt "1ページにNページ集約するか?" default items (item 1 of listNup) OK button name "OK" cancel button name "キャンセル" with multiple selections allowed without empty selection allowed)
on error
log "エラーしました"
return
end try
if objResponse is false then
return
end if
####戻り値確定
set numNup to (objResponse) as text


####選んでもらうリスト
set listDirs to {"LU", "LD", "RU", "RD"} as list
####ダイアログ
try
set objResponse to (choose from list listDirs with title "選んでください" with prompt "LU右下->右上\nLD右上->右下※\nRU左下->左上\nRD左上->左下※\n通常上から下です" default items (item 2 of listDirs) OK button name "OK" cancel button name "キャンセル" with multiple selections allowed without empty selection allowed)
on error
log "エラーしました"
return
end try
if objResponse is false then
return
end if
####戻り値確定
set strDirs to (objResponse) as text

####パス整形
tell application "Finder"
set aliasPathToMe to (container of (path to me)) as alias
set thePathToMe to (POSIX path of aliasPathToMe) as Unicode text
end tell
####コマンドへのパス
set strPyPath to ("" & thePathToMe & "bin/pdfNup.py")
#####ページ数があればファイルを開いている
tell application "Adobe Acrobat"
activate
tell active doc
tell PDF Window 1
####ページ数
try
set numAllPages to count of every page
on error
display alert "エラー:pdfを開いていません" buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 10
return
end try
end tell
create thumbs
end tell
end tell
############
#####開いているファイルのパスを取得する
tell application "Adobe Acrobat"
activate
tell active doc
set aliasFilePath to file alias as alias
set strFileName to name as text
end tell
end tell
#####保存先のパスを設定して
set strDistName to doReplace(strFileName, ".pdf", "") as text
set strDistFileName to ("" & strDistName & "-" & numNup & "up.pdf") as text
set theFileDir to (POSIX path of aliasFilePath) as Unicode text
#####同名ファイルがある場合は中止
tell application "Finder"
set aliasDistDir to (container of aliasFilePath) as alias
set boolFileExists to exists (file strDistFileName of folder aliasDistDir)
if boolFileExists is true then
display alert "エラー:ファイルがすでにあります移動してください" buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 10
return
end if
end tell
#####ファイルパス確定
set strFilePath to POSIX path of aliasFilePath as text
#####コマンドライン整形
set strCommandText to ("python3 \"" & strPyPath & "\" \"" & strFilePath & "\" " & numNup & " " & strDirs & "") as text
log strCommandText
#####コマンド実行
do shell script strCommandText
####出来上がったファイルを開く
tell application "Finder"
set aliasDistDir to (container of aliasFilePath) as alias
set boolFileExists to exists (file strDistFileName of folder aliasDistDir)
if boolFileExists is true then
set aliasDistFile to (file strDistFileName of folder aliasDistDir) as alias
tell application "Adobe Acrobat"
activate
open aliasDistFile
end tell
end if
end tell
######集約完了



####拡張子おきかえで使うサブ
to doReplace(theText, orgStr, newStr)
set oldDelim to AppleScript's text item delimiters
set AppleScript's text item delimiters to orgStr
set tmpList to every text item of theText
set AppleScript's text item delimiters to newStr
set tmpStr to tmpList as text
set AppleScript's text item delimiters to oldDelim
return tmpStr
end doReplace


#!/usr/bin/env python3

# coding: utf-8

##from datetime import datetime

##import os

import sys

import urllib.parse

######

from pdfnup import generateNup

## 

##generateNup("test-legal-p.pdf", 8, verbose=True)


argGetData = sys.argv

strFilePath = str(argGetData[1])

numNup = int(argGetData[2])

strDirs = str(argGetData[3])


##generateNup(strFilePath, 2,  verbose=True)


##右ページ->左ページの読み順

##下から上に

##generateNup(strFilePath, 2, dirs="RU", verbose=True)

##上から下に

##generateNup(strFilePath, 2, dirs="RD", verbose=True)


##左ページ-->右ページ 

##下から上に

##generateNup(strFilePath, 4, dirs="LU", verbose=True)

##上から下に

##generateNup(strFilePath, 4, dirs="LD", verbose=True)


print(strFilePath)

print(numNup)

print(strDirs)



if strDirs == "RU":

    generateNup( strFilePath , numNup , dirs="RU", verbose=True)

elif strDirs == "RD":

    generateNup( strFilePath , numNup , dirs="RD", verbose=True)

elif strDirs == "LU":

    generateNup( strFilePath , numNup , dirs="LU", verbose=True)

elif strDirs == "LD":

    generateNup( strFilePath , numNup , dirs="LD", verbose=True)


##

|

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat AddOn Acrobat Annotation Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat JS Acrobat Manifest Acrobat Menu Acrobat Open Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat python Acrobat Reader Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin Support Admin System Information Admin Tools Admin Users Admin Volumes Adobe Adobe FDKO Adobe RemoteUpdateManager AppKit Apple AppleScript AppleScript do shell script AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript System Events AppleScript System Events Plist AppleScript Video Applications AppStore Archive Attributes Automator BackUp Barcode Barcode QR Barcode QR Decode Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome CIImage CityCode CloudStorage Color com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time delimiters Desktop Device Diff Disk Dock DropBox Droplet eMail Encode % Encode Decode Encode UTF8 Error EXIFData ffmpeg File Finder Firefox Folder FolderAction Fonts GIF github Guide HTML HTML Entity Icon Illustrator Image Events Image2PDF ImageOptim iPhone iWork Javascript Jedit Json Label Leading Zero List locationd LRC lsappinfo LSSharedFileList m3u8 Mail MakePDF Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Mouse Music NetWork Notes NSArray NSArray Sort NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSColor NSColorList NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSPrintOperation NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth OneDrive PDF PDFAnnotation PDFAnnotationWidget PDFContext PDFDisplayBox PDFDocumentPermissions PDFImageRep PDFKit PDFnUP PDFOutline perl Photoshop PlistBuddy pluginkit postalcode PostScript prefPane Preview Python QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver SF Symbols character id SF Symbols Entity sips Skype Slack Sound Spotlight sqlite SRT StandardAdditions Swift System Settings TCC TemporaryItems Terminal Text Text CSV Text MD Text TSV TextEdit Tools Translate Trash Twitter Typography UI Unit Conversion UTType valueForKeyPath Video VisionKit Visual Studio Code Wacom webarchive webp Wifi Windows XML XML EPUB XML OPML XML Plist XML RSS XML savedSearch XML SVG XML TTML XML webloc XML XMP YouTube zoom