Getting Page count with AppleScript
Hi Everyone,
It been a long time since I visited so I hope everyone is well.
Does anyone know how to get the page count of a document with Applescript. The best I've done is to divide the total number of words by the average amount of words on a page. This isn't perfect but it give me something close. I'm using the following snippets to get the info, which is being used to popular real time statitics about the progress of book four on my website.
set WordCount to word count
set ParagraphCount to paragraph count
set PageCount to round (WordCount / 184)
set CharacterCount to character count
Paragraph count doesn't seem to come too close either. I think it just adds up the number of carridge returns in the document.
Cheers
Chris
http://www.thomasstrange.com
<pre>tell application "Pages"
tell document 1
page count
end tell
end tell</pre>
For me, the result matches the actual number of pages.
As for paragraph count, I assume you want to skip empty paragraphs.
The obvious "length of paragraph 1" doesn't seem to work, so here's a less than optimal solution:
<pre>tell application "Pages"
tell document 1
tell body text
set paragraphCount to 0
repeat with aParagraph in every paragraph
if length of (contents of aParagraph as text) > 1 then
set paragraphCount to paragraphCount + 1
end if
end repeat
end tell
end tell
end tell
paragraphCount</pre>
Titanium PowerBook Mac OS X (10.4.10)
Similar Messages
-
How to get Page Count of pdf in Document library in EventHandler
Hi,
How to get Page Count of pdf in Document library once uploaded has been done and i would like to update the page count value in document library column of the corresponding file.
I should achieve it in Event handler.
Which even should i use, either ItemAdded or "ItemUpdated "?
Thanks & Regards
Poomani Sankaran.Hello,
If you are looking for file download or view count then event handler will not work. You need to enable the analytic report to your site. Once you enable it then you can see the report within a browser or you can also create custom webpart to show count
of specific file.
http://blogs.msdn.com/b/ecm/archive/2010/05/03/web-analytics-in-sharepoint-2010-insights-into-reports-and-metrics.aspx
http://sharepoint.stackexchange.com/questions/34611/count-of-files-under-a-folder-in-a-document-library
Hope it could help
Hemendra:Yesterday is just a memory,Tomorrow we may never see
Please remember to mark the replies as answers if they help and unmark them if they provide no help -
Report.Services 2008 - get page-count or row-count in the c#-code
hello
is it possible to get from the ReportViewer-control / ServerReport the page-count or row-count after the
reportViewerCheck.ServerReport.Refresh();
statement ??
many thanks in advance for any clue & regards
MichaelHi Michael,
Yes, you can get them. For row count, you can add a parameter to store the row count of your dataset in your report.
Here are the steps:
1. Add 2 datasets in your report, one for report use and the other on is to row count use. For instance:
DataSet1: SELECT HumanResources.vEmployee.* FROM HumanResources.vEmployee
DataSet2: SELECT COUNT(*) FROM HumanResources.vEmployee
2. Add a parameter, set the parameter’s default value set to Get Values from a query and select DataSet2.
Then, in your ASP.NET web application code you can use the following function to get the row count of the report:
private int GetReportRowCount(ReportViewer report)
return Convert.ToInt32(report.ServerReport.GetParameters()[0].Values[0].ToString());
For page count, you can refer to the following code:
private int GetReportPageCount(ReportViewer report)
return report.ServerReport.GetTotalPages();
You may not get the correct row count and page count in after executing Refresh () method, that’s because when you run this method, it will start another thread to refresh the report and the code below Refresh () method will not wait refreshing complete but run it. For instance, you may get the page count as o if you run the following code in the Button event:
// Click this Button to refresh the ReportViewer1
protected void btnGetPageCount_Click(object sender, EventArgs e)
// Refresh the ReportViewer1
this.ReportViewer1.ServerReport.Refresh();
// Get ReportViewer1's page count and display in the txtPageCount TextBox
this.txtPageCount.Text = this.ReportViewer1.ServerReport.GetTotalPages().ToString();
You can run the refresh in separate events and get page count in another event, such as below code:
// Click this Button to refresh the ReportViewer1
protected void btnGetPageCount_Click(object sender, EventArgs e)
// Refresh the ReportViewer1
this.ReportViewer1.ServerReport.Refresh();
// Display the txtPageCount's text to ReportViewer's page count
protected void btnGetPageCount2_Click(object sender, EventArgs e)
// Get ReportViewer1's page count and display in the txtPageCount TextBox
this.txtPageCount.Text = this.ReportViewer1.ServerReport.GetTotalPages().ToString();
Hope this helps! I would suggest you post a new thread in Visual Studio Report Controls forum if you need more help about using ReportViewer in ASP.NET web application.
Please remember to mark the replies as answers if they help and unmark them if they provide no help. -
Getting Page Count for a Multi-Page PDF file using Illustrator script?
Does anyone know how to get the page count of a multi page PDF file? I know you can then open each page using the PDFFileOptions (pagetoopen). But I need to know up front how many pages there are to loop thru to open each page and process each page.
Any Ideas?This script i did for photoshop:
OK so lets do it working on WIN and MAC without any shell script.
This solution is not the best but its working.
I used Try catch to solve it.
Only issue is that you should at least somehow know how many pages you expect in pdf.. this mean if you are working with books or flyers...
Then set the maxPagesCount to that number.
I am working with pdfs with max 20pages.. so i start open the 20 then 19 then 18 and when i am success i know the amount of pages.
Its not the quicker way but its usable.
var maxPagesCount = 20;
var actPagesCount = maxPagesCount;
var opts1 = new PDFOpenOptions();
opts1.usePageNumber = true;
opts1.antiAlias = true;
opts1.bitsPerChannel = BitsPerChannelType.EIGHT;
opts1.resolution = 10; //it will load faster the test page
opts1.suppressWarnings = true;
opts1.cropPage = CropToType.MEDIABOX;
myFunction = function () {
try {
app.displayDialogs = DialogModes.NO;
var fileList = openDialog();
for (i = 0; i < fileList.length; i++) {
actPagesCount = maxPagesCount;
getPagesCount(fileList[i],maxPagesCount);
alert(actPagesCount);
} catch (exception) {
alert(exception);
getPagesCount = function (checkFile, lastPageID) {
try {
for (var checkPage = lastPageID; checkPage > 0; checkPage--) {
opts1.page = checkPage;
var docRef = open(checkFile, opts1, false);
docRef.close(SaveOptions.DONOTSAVECHANGES);
actPagesCount = lastPageID;
return;
checkPage=0;
} catch (exception) {
// Look for next page
checkPage--;
getPagesCount(checkFile,checkPage); -
Get Page Count of PDF using Publication Post Processing Plugin
Hi,
I am using the publiching functionality of BOXI 3.1 to create a large volume of PDFs. I have a report that I am publishing using a publication with a post processing plugin applied after distribution. I need to get the total page count of the pdf and store this value in the database. Becuase I am already using a post processing plugin after distribution, it would be ideal to extract it there...but I cannot figure out how to get the value at this point.
Currently we parse the actual binary pdf file, but I know that Crystal and BOXI know this total page count and some point in the processing cycle. Does anyone know how to get at the total page count of each pdf/report instance?
Thanks,
KristinaI would post-process the PDF file as you're doing.
The total page count isn't metadata - it's something computable from the report instance, that is lost after the PDF is generated.
Trying to work with that would lead to a more complex workflow - i.e., schedule to report format, open the report instance using a reporting SDK, calculate the total page count, export using the reporting SDK to PDF, add the PDF to the publication artifact and remove the report instance, other steps I may have missed....
Sincerely,
Ted Ueda -
How can I get record count with a query?
In Client/Server pplication,the client send a query to server.
How can server get record count by oracle call interface?
Is it need execute "select count(*) from ...."?Yes.
Either that or increment a counter for each record fetched and
loop round until you hit the last record.
The first method would be more efficient on large datasets. -
Inserting text into a Pages document with Applescript
I want to create a Pages document from a custom template but be able to insert text at various points in the document (inputted data under headings etc). I would like to use Applescript but cannot get insertion points to work, is this possible? As usual, all help gratefully accepted.
I have made a Pages template that contains tables and I want to enter text into sections of these tables
That's a completely different story! But that's still possible using GUI Scripting. Here's an example:
tell application "Pages"
activate
select table 1 of body text of front document
tell application "System Events" to tell process "Pages"
set theWindow to window 1 whose role description is "standard window"
click button "Table" of tool bar 1 of theWindow
keystroke "Cell A1"
keystroke tab
keystroke "Cell B1"
key code 125 -- down arrow
keystroke "Cell B2"
-- and so on
end tell
select insertion point after table 1 of body text of front document
end tell -
Get page count within c# WinForm app
Hello every body,
I have a winform application that shows a crystal report through the WinForm Crystalreportviewer.
Is there a way to get in my c# application the total number of pages generated in the report?
Thank You
Giovanni PerroneYou will want to search the forums for questions like this prior to posting as this was answered about 10 threads down from yours.
Get TotalPageCount or last page number
I have not tried it in CR2008 and C# so let me know how it goes.
Good luck.
Jason -
Most efficient way to get row count with a where clause
Have not found a definitive answer on how to do this. Is there a better way to get a row count from a large table that needs to satisfy a where clause like so:
SELECT COUNT(*) FROM BigTable WHERE TypeName = 'ABC'
I have seen several posts suggesting something like
SELECT COUNT(*) FROM BigTable(NOLOCK);
and
selectOBJECT_NAME(object_id),row_count from sys.dm_db_partition_stats
whereOBJECT_NAME(object_id)='BigTable'but I need the row count that satisfies my where clause (i.e.: WHERE TypeName = 'ABC')It needs index to improve the performance.
- create index on typename column
- create a indexed view to do the count in advance
-partition on type name (although it's unlikely) then get count from the system tables...
all those 3 solutions are about indexing.
Regards
John Huang, MVP-SQL, MCM-SQL, http://www.sqlnotes.info -
How to process received images in iChat/Messages with Applescript
Hello!
I want to process all received photos or videos with Applescript.
I try this:
using terms from application "Messages"
on message received theMessage from theBuddy for theChat
if the length of theMessage is 0 then
-- it means I received a picture or video file, but I can't get the file with Applescript, because theMessage is an empty string and not a file
set theMessage to "<lost photo or video content>"
else
-- it's OK, I just got a text message and I can now save it or display or do something else with it
end if
end message received
end using terms from
But if I receive a photo, theMessage is empty.
The event handlers "on completed file transfer" and "received file transfer invitation" don't work in this case, probably because it is not a file tranfer, but sort of an inline picture.
I use OS X 10.8.
Can somebody help me?I have a similar question as well. I tried this for you and nothing happened.
on received file transfer invitation theFileTransfer
end received file transfer invitation
I think "completed file transfer" is regarding to the file being transfered to Apple's Server from your computer when a file is sent, but I'm not sure about "received file transfer invitation." Regarding it being an inline file, maybe try using the attachment class.
attachment n [inh. rich text] : Represents an inline text attachment. This class is used mainly for make commands.
elements
contained by rich text, characters, paragraphs, words, attribute runs.
properties
file (file, r/o) : The path to the file for the attachment syn file name -
Opening Pages automaticly with Spaces
Does anyone know how to get Pages started with Spaces automaticaly without having to open a Dokument first?
Well let me explain. I've got Pages into the first Window in "Exposé & Spaces. So wenn I start the Computer, all programms that I put in there, are being automaticaly started. But wenn I press "ctrl" and "1" for getting into the first Spaces, Pages is not activated like for example Safari or Mail. I first have to go to the shortcuts and push the "Pages" button to activate the program. But i try with your sugestion and see if it works. Thanks anyways.
-
Hello, I'm a beinnger apple scripter, and I have 2 questions. First, im trying to find the code to generate a page count for the front document of preview. I tried something like this:
choose file with prompt "Count the number of pages in this PDF file:" without invisibles
do shell script "/usr/bin/mdls -name kMDItemNumberOfPages " & quoted form of POSIX path of result & " | /usr/bin/grep -o '[0-9]\\+$'"
But I dont want to have to choose a file with the prompt, and Im not sure how to get the path or POSIX path of an open pdf that is the front document in prievew to then use that directory to select the file to run the shell script on. This is one step in a much larger sequence of automator/apple script commands for large print jobs.
The large scale view is:
1. seleting a group .musx Finale 2014 files and creating pdfs of all the documents
-Achieved with Automator stuff: [Get selected finder items] [open finder items with Finale 2014] [run applescript to convert to pdf all the open files] (which I have working but without a proper repeat condition)
2. sorting those those exports into even/odd groups
3. making the even pages 2 up with a create booklet plugin
3. combinging even/odd group pdfs in their respective folders
4. sending the 2 up evens to 1 printer, and the singes to another printer.
but at this stage in the code/automator this is what i'll need to be doing:
1. Several pdf documents will be open and I need to determine the page count of the front document.
2. With that result I need to determine if the pagecount is even or odd.
3. If its even, I need to save as pdf in a file folder /desktop/PDF Export/Doubles
- if its odd, I need to save as pdf pages from 1 to (pageCount -1) to /desktop/PDF Export/Doubles, and pages (pageCount) to (pageCount) to desktop/PDF Export/Singles. (example: A 5 page pdf will send pages 1-4 to folder "Doubles", and pages from 5 to 5 to Singles, A 1 page pdf will only send a copy to the folder "Singles." A 2 page pdf will send both pages to "doubles"
4. once the even/odd pages have had pdfs made in the either or both of the folders, Im going to close the document and repeat for all other open pdfs.
Which also brings me to my 2nd repeat condition question: how can I repeat (print, save as pdf, close) commands for open files and end the script once all files are closed? This can help me both at this stage, as well the coding stage before in creating the pdfs from open Finale/sibelius .sib/.musx files
would it be something like this?:
If front document exists
try
tell application "preview"
<bla bla>
end try
end tell
At stage 1 of the large scale i've gotten the files to export pdfs and close multiple files, but if i say "repeat 4 times" and i have 3 files it can do those commands but it gets stuck trying to repeat the code one more time. I need the repeat amount x to be the # of items in selection from the the original finder window.
Thanks for the help!The following AppleScript will get the POSIX path and filename of the current PDF file. It will just return the integer value for page count. Note: The path retrieved is the actual path to the PDF file, unless it is on the Desktop. In the latter case, the path will be ~/Library/Containers/com.apple.Preview/Data/Desktop/filename.pdf.
The script assumes that the following folders exist, otherwise you will need a try block to test for their presence.
The AppleScript dictionary for Preview does not provide a page dictionary entry, that would make a repeat loop and page range possible for saving individual page ranges.
set pdfDoubles to POSIX path of ((path to desktop) & "PDF Export" & Doubles)
set pdfSingles to POSIX path of ((path to desktop) & "PDF Export" & Singles)
tell application "Preview"
-- gets quoted POSIX path and filename
set pdfFile to (get path of front document)
set pdfName to (get name of front document)
log pdfName
set cmdArg to "/usr/bin/mdls -name kMDItemNumberOfPages " & pdfFile ¬
& " | egrep -o \"(\\d+)\""
set pageCnt to do shell script cmdArg
display dialog pageCnt
if pageCnt mod 2 is 0 then
-- even
-- save pdfName in pdfDoubles
else
-- save pdfName in pdfDoubles
-- save individual pages in pdfSingles
end if
end tell -
How do you get word count to print at the end of a document in Pages?
How do you get word count to print at the end of a document in Pages?
Pages v5 does not provide a user assignable word count variable. With some AppleScript, and a paste operation from the clipboard, you can have locale punctuated word count in this format: 7,803 — anywhere in your document. The following AppleScript works with Pages '09 v4.3 through Pages v5.5.2 on Yosemite.
I would suggest that you copy paste the following AppleScript into your [Apple] Script Editor and save it (suggestion) wordcnt.applescript. Then, follow this with an option+Save As… and this time set the File format to Script Bundle, or Application with hidden extension — saved to your Desktop. Provided you have a Pages document open, you are then a double-click from the ability to paste your current word count into Pages.
Note: If you have Pages word count display enabled, it will automatically count your pasted value as another word which initially may deceive on true word count at the time the script was run.
AppleScript
--- copy below this line ---
property locale : "en_US.UTF-8" -- In Terminal, use the locale command to see yours
if not ApplicationIsRunning("Pages") then
display dialog "Pages must be running to use this utility."
return quit
end if
tell application "Pages"
tell body text of front document
set wordCnt to count words
-- Don't want punctuated numbers? Remove the single quote from printf format
set the clipboard to (do shell script "export LC_ALL=" & locale & "; printf \"%'d\" " & wordCnt)
end tell
end tell
on ApplicationIsRunning(appName)
tell application "System Events" to set appNameIsRunning to exists (processes where name is appName)
return appNameIsRunning
end ApplicationIsRunning -
Can not add function to pages-document created with Applescript
If I create new document using the GUI (New document) I can place the cursor within any table-cell, type "=" (equal sign) and f.e. "2+2" which will result in a cell showing a "4".
If I create a document with Applescript, I can not add new functions (neither by typing = nor by using Insert >> Function (may be different, I have German version here). Already existing functions (which already were in the template) can still be used and work as expected but can not be altered.
Any idea?
I use Pages '08, Version 3.03
Code I used to create the document:
tell application "Pages"
launch
make new document at front with properties {template name:templateName}
# Angebotsnummer ins Dokument schreiben
tell body text of front document
make new paragraph at after paragraph 1 with data angebotsNr
set paragraph style of paragraph 2 to "Überschrift"
end tell
# Datei abspeichern
set dateiName to missing value
repeat until dateiName is not equal to missing value
set dateiName to text returned of (display dialog "Datei Name:" default answer angebotsNr & "_" & kundenName) as text
end repeat
save front document in angebotsOrdner & dateiName
end tellI apologize but the given script can't run.
The variable templateName is undefined.
The variable angebotsNr is undefined too.
About the described behavior, it's a bug which I never discover before.
It's always striking in Pages '09.
Here is the report which I filed :
Bug ID# 8704270
Summary:
+Odd behavior of tables in Pages documents created by a script+
+Steps to Reproduce:+
+Run this huge script+
+tell application "Pages"+
+make new document at front with properties {template name:"Blank"} (* "Vierge" on French systems *)+
+end tell+
+Insert a table+
+try to insert a formula+
+Expected Results:+
+I assumed that I will get the formula editor which I get when the document is created by hand+
+Actual Results:+
+There is no way to get the editor, no way to insert the equal character.+
+This odd behavior strike in all versions of Pages '09 and Pages '08+
Regression:
+None to my knowledge+
Yvan KOENIG (VALLAURIS, France) dimanche 28 novembre 2010 11:30:29 -
How can I get a total page count of a PDF before placing every page in the PDF?
Before the [long] spiel, I'm using javascript in InDesign CS3.
I'd like to create a script that places a multiPage PDF in any number of different impositions. (saddle stitch, 4up signatures, 16up signatures etc.)
I've easily created a script that iterates through a PDF and places it into a new document as (4,1|2,3), (8,5|6,7) etc, which works for printing in duplex, folding each page in half, and gluing the resulting spines to make a simple thick book (for PDFs with more than, say, 64 pages).
However, the next step is to re-write the script to create a saddle stitch document (16,1|2,15), (14,3|4,13) ... (10,7|8,9). For this I need to know how many pages there are in the PDF before I start placing the PDF pages, and then making the new document [int((PDFpages+3)/4)] pages long.
Is there a simple way to get the count of PDFpages without going through a loop and placing the next page from the PDF until the placed page number equals the first page number?
This way seems wasteful:
var totPDFPages = 1;
app.pdfPlacePreferences.pageNumber = totPDFPages;
myPDFPage = sheetFront.place(File(srcPDF), [0,0])[0];
var pdfFirstPage = myPDFPage.pdfAttributes.pageNumber;
while (doneCounting == false) {
totPDFPages += 1;app.pdfPlacePreferences.pageNumber = totPDFPages;
myPDFPage = sheetFront.place(File(srcPDF), [0,0])[0];
if (myPDFPage.pdfAttributes.pageNumber == pdfFirstPage) {
totPDFPages -=1;
doneCounting = true;
alert("PDF has " + totPDFPages + " pages!");exit();
myPDFPage.remove();
NB. Javascript above *hasn't* been run, but should look similar once debugged.
The only thing I've though of to relieve the sheer duplication of placing the PDF twice (once for the count, and once for the imposition), is to create an array of impoPages[counter]=myPDFPage, and then shuffle the pages referenced by the array to the correct sheet and position.
It'd be much easier to be able to assign pageCount = File(srcPDF).pageCount !!!
Thanks for any help/tips or even a simple "What are you smoking, man!?"
Cheers,
Jezzthis will get almost all pdf pages count.
jxswm
function getPDFPageCount(f){
if(f.alias){f = f.resolve();}
if(f == null){return -1;}
if(f.hidden){f.hidden = false;}
if(f.readonly){f.readonly = false;}
f = new File(f.fsName);
f.encoding = "Binary";
if(!f.open("r","TEXT","R*ch")){return -1;}
f.seek(0, 0); var str = f.read(); f.close();
if(!str){return -1;}
//f = new File(Folder.temp+"/123.TXT");
//writeFile(f, str.toSource()); f.execute();
var ix, _ix, lim, ps;
ix = str.indexOf("/N ");
if(ix == -1){
var src = str.toSource();
_ix = src.indexOf("<< /Type /Pages /Kids [");
if(_ix == -1){
ps = src.match(/<<\/Count (\d+)\/Type\/Pages\/Kids\[/);
if(ps == null){
ps = src.match(/obj <<\\n\/Type \/Pages\\n\/Count (\d+)\\n\/Kids \[/);
if(ps == null){
ps = src.match(/obj\\n<<\\n\/Type \/Pages\\n\/Kids \[.+\]\\n\/Count (\d+)\\n\//);
if(ps == null){return -1;}
lim = parseInt(ps[1]);
if(isNaN(lim)){return -1;}
return lim;
lim = parseInt(ps[1]);
if(isNaN(lim)){return -1;}
return lim;
lim = parseInt(ps[1]);
if(isNaN(lim)){return -1;}
return lim;
ix = src.indexOf("] /Count ", _ix);
if(ix == -1){return -1;}
_ix = src.indexOf(">>", ix);
if(_ix == -1){return -1;}
lim = parseInt(src.substring(ix+9, _ix));
if(isNaN(lim)){return -1;}
return lim;
_ix = str.indexOf("/T", ix);
if(_ix == -1){
ps = str.match(/<<\/Count (\d+)\/Type\/Pages\/Kids\[/);
if(ps == null){return -1;}
lim = parseInt(ps[1]);
if(isNaN(lim)){return -1;}
return lim;
lim = parseInt(str.substring(ix+3, _ix));
if(isNaN(lim)){return -1;}
return lim;
Maybe you are looking for
-
made in cosmos help please need it using System; using Cosmos.Compiler.Builder; using System.Threading; using System.Windows.Forms; namespace IUOS class Program #region Cosmos Builder logic // Most users wont touch this. This will
-
How do i update a mac ipod to a windows system without deleting the music
I got an ipod mini hp 6gb and first used it on an imac with itunes 4.7. now i want to update it to a windows xp system and i was wondering if there is a way i can make it work without deleting my music. is there some sort of app or something because
-
I bought a new computer and transferred everything across. When I tried to download podcast on to iphone 3gs it said it was not authorised. I authorised it but each time I try to download it says I am not but when I go to authorise it says it is alre
-
If i have two option to select between XI or BW which one in better and why
if i have two option to select between XI or BW which one in better and why both in terms of money and in terms of my career growth.......
-
How to embed BARCODE into smartform ?
Hi All, I have a requirement to embed an EAN-128 barcode for handling unit(EXIDV) and other fields in a shipping label(smart form).please let me know how should I send the value for these · start code · FNC1 · application ident