Print multipage PDF on different printer-trays - php

I am generating a PDF by PHP with FPDF. This works well.
Now what I want:
From a multipage PDF all pages expect the last one have to print with paper from tray1 and the last page from tray2.
Now the Question:
How is this possible? Is this a Acrobat Reader issue? Can it be done with JavaScript in PDF?

It is not possible, as PDFs do not contain any information on the printer trays or other information. It is actually set in the printer instructions through the client's printer driver, who has to provide this information to the client program. If you need this functionality for batch processing, you'd have to leave PHP and get on the client side, e.g. through the Acrobat SDK, in which you can give this information, e.g. on a PostScript printer via the SetPageDevice-function

I use CUPS on an intranet website. I don't specify a tray and my code is ruby, but the principle definitely works.
Here's my code, see if you can adapt it for your scenario
def print(path)
raise ArgumentError, "'#{path}' does not exist" unless File.file?(path)
`lp -s -d printer_name -h 127.0.0.1 -o page-ranges=1-4 -o media=A4,Upper #{path}`
$?.to_i == 0 ? true : false
end
The basic idea is to generate the PDF, save it to disk then call this method to shell out to CUPS. You might need to play with the media option to get it doing what you need. 'Upper' is the tray you're targeting.
Make sure path is sanitised before being passed to this method or you risk opening a security hole.

PHP can send some things to a print server like CUPS, but it can't get something to print on a client's machine save through JavaScript. JavaScript does not have the ability to control the individual's printer settings when being called from a browser. And while there are bindings for embedded PDF's in JS, there is no guarantee that the user will not simply have the file open in a standalone PDF reader (my computer at home is configured this way).

For future readers of this post, if a commercial library is a valid choice then it is possible to do this with Amyuni PDF Creator ActiveX (Delphi, C++, VB, PHP) or with Amyuni PDF Creator .Net (C#, VB.net, etc.) by changing the "PaperBin" property of a page object.
Possible values for this property can be found in the documentation for the DEVMODE structure in MSDN, examples: DMBIN_UPPER - 0x0001, DMBIN_LOWER - 0x0002, DMBIN_AUTO - 0x0007.
The code in C# would look like this:
Amyuni.PDFCreator.IacDocument pdfDoc = new Amyuni.PDFCreator.IacDocument();
using(FileStream fs = File.Open("MyDocument.pdf", FileMode.Open))
{
pdfDoc.Open(fs, "");
}
const int DMBIN_MANUAL = 4;
for( int pageNumber = 1; i <= pdfDoc.PageCount; i++)
{
pdfDoc.GetPage(pageNumber).AttributeByName("PaperBin").Value = DMBIN_MANUAL;
}
pdfDoc.Print("My Laser Printer", False);
For PHP, you will need to use the ActiveX version, and create the document using the ProgID of the ActiveX control:
$pdfdoc = new COM("PDFCreactiveX.PDFCreactiveX");
Note that this approach is about printing to a specific tray using the library, as other answers have mentioned, it is not possible to store this information in the PDF file itself so that it can be used by other applications.
Disclaimer: I currently work for Amyuni Technologies.

Related

Using F# scripts like php instead of with asp.net core

So I was wondering if you could use F# with fsi.exe to run server side scripts to serve html pages. Basically, could you use it like php? If you can, would it be very practical to use it like that? Also, even if this is not very practical, I would be interested in if this would somehow be possible.
PHP and for that matter Classic ASP pages on a web site typically map one-to-one to script files on the file system on a web server.
If you implement ASP.Net's IHttpHandler you could execute F# scripts on the file system in response to HTTP requests. The IHttpHandler's ProcessRequest method passes a HttpContext instance which could be used for reading the Request arguments and setting the Response. This could be passed to a well-known function implemented, say "handler", in the F# script.
type HttpHandler() =
interface IHttpHandler with
member this.ProcessRequest(context:HttpContext) =
let localpath = context.Server.MapPath(context.Request.FilePath)
let a = compile localpath // where compile creates an assembly from an fsx file
let mi = getHandler a // where getHandler gets a function using reflection
mi.Invoke(null, [|context|])
The F# Compiler Services provides FSharperChecker API which could be used to compile F# script files to dynamic assemblies.
let compile path =
let checker = FSharpChecker.Create()
let errors, exitCode, dynamicAssembly =
checker.CompileToDynamicAssembly([| "-o"; path; "-a"; path |], execute=None)
|> Async.RunSynchronously
dynamicAssembly
The dynamic assemblies could then be used to invoke functions via reflection, passing the HttpContext value.
let getHandler a =
a.GetTypes() |> Seq.pick (fun ty ->
match ty.GetMethod("handler", [|typeof<System.Web.HttpContext>|]) with
| null -> None
| mi -> Some mi
)
So that your script file might look something like this:
let handler (context:System.Web.HttpContext) =
context.Response.Write("Hello World")
Finally there are a plethora of F# DSLS for generating HTML from code, I have a simple one called FsHtml.
Giraffe with the Razor view engine might be the best fit for what you're after: https://github.com/giraffe-fsharp/Giraffe.Razor
It provides a nice way to define API routes functionally and a nice clean syntax for HTML templates.
It does use asp.net core though - I'm not sure what you're trying to achieve by avoiding this so apologies if my answer is a little off-target.
You can compile .fsx scripts with Fable (see here: https://axxes.com/en/net/compiling-f-scripts-with-fable-2-2/) as Just another metaprogrammer has mentioned, though personally it's not my preferred approach (I'm happy with .fs) and I'd argue that it's more akin to react / jsx since it's client side and uses react under the hood.

read a password-protected page

I'm trying to read specific div-elements of a website with a script either written in php or perl.
Unfortunately, the page requests a login before those specific site can be read. As I can see, it's ssl-protected. I'm not looking for a complete solution, I just need a hint regarding the best way to tell the script the informations needed for logging in (user+password), before reading parts of the sourcecode of the page that comes afterwards.
I'm not quite sure if it's better to do this with PERL or PHP, so i have tagged this question with both of these languages.
Mojo::UserAgent (see cookbook) has a built-in cookie jar and can do SSL if you have IO::Socket::SSL installed. It has a DOM parser which can easily use CSS3 selectors to traverse the returned result. And if that wasn't good enough, the whole thing can be used non-blocking (if that's something you need).
Mojo::UserAgent and the other tools listed above are parts of the Mojolicious suite of tools. It's a Perl library, and I would certainly recommend Perl for this task since it is a more general purpose language than PHP is.
Here is a very simplistic example to get the text from all the links that are inside a div with a class myclass
use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;
$ua->post( 'http://mysite.com/login' => form => { ... } );
my #link_text =
$ua->get( 'http://mysite.com/protected/page' )
->res
->dom('div.myclass a')
->text
->each;
In fact, running this shell command may be enough to get you started (depending on permissions)
curl -L cpanmin.us | perl - -n Mojolicious IO::Socket::SSL

Scala Lift - Run PHP file from within scala runtime

I'm not entirely sure the wording for the title is correct, but what I'm attempting to do is run and execute PHP files from within the Lift framework.
I'm not after any url queries to a PHP file residing on a server, more interested in somehow getting the PHP runtime working through my Scala/Lift app.
Use case: I have my app packaged into a .war file, I host this via a cloud provider. I upload code snippets to said app which then runs the php file and does whatever necessary.
I've seen various posts regarding Bianca but am hoping to keep this setup light and require only the PHP binary itself and a little code to get it flying.
Thanks in advance, please let me know if you need me to elaborate :)
“Never say never, because limits, like fears, are often just an
illusion.”
― Michael Jordan
What you really need is an open source (GPL), embeddable, full PHP 5 implementation, written entirely in Java!
Caucho's Quercus PHP Java runtime is just that, and it will let you run PHP within a Java app without external libraries or native code.
Below is a Quercus-PHP-in-Java code sample I found in this answer
import javax.script.ScriptEngine;
import com.caucho.quercus.script.QuercusScriptEngineFactory;
QuercusScriptEngineFactory factory = new QuercusScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine();
String phpCode = "<?php $foo = strlen('abc'); print $foo; return 'yikes'; ?>"; //PHP Code as String
Object o = engine.eval(phpCode);
System.out.println(o);
It should be little effort to convert this code to idiomatic Scala. Obviously, the 'phpCode' variable could be constructed from external PHP file contents etc.
Let us know how you get on ;-)
That's a bit of an odd requirement, but if it's what you need to do, you can use a ProcessBuilder to execute and interact with your PHP script from the command line.

How do I check if an swf flash file implements clickTAG?

We've been developing an affiliate system and would like to detect somehow that a compiled, SWF advert implements clickTAG or not. Is there any way to automate this process?
When I debug flash banners I use flasm (http://www.nowrap.de/flasm.html windows+linux) to decompile the swf file. You can both get output to console (-d) or dump it to a file:
$ flasm -d file.swf > out.txt
Then search the file/output for clickTag/clickTAG.
Requires exec privileges.
This is a complex problem.
The suggested solution only addresses the case of an incorrect clicktag (e.g. clickTAG vs clickTag). Here are other potential problems:
- no clickable layer, no clicktag code
- clickable layer with hard-coded URL
- clickable layer only covering a small portion of the banner
- All of the above in AS3 (flasm only supports AS2)
http://adopstools.net lets you submit a swf and check it for clicktags as well as other things
If I've understood correctly what you need to do, it should be possible to build a semiautomated testing swf by loading the ad, then simulating clicks on everything in its display tree.
You can pass parameters to a loaded swf using the data property of a URLRequest like so:
var loader:Loader = new Loader();
var req:URLRequest = new URLRequest("ad.swf");
var clickTagURL:String = "http://www.example.com";
req.data = new URLVariables("clickTAG=" + clickTagURL + "&clickTag=" + clickTagURL + "&clicktag=" + clickTagURL);
loader.load(req);
(Though you'll need to run that in a browser or standalone as the Flash IDE complains about query string parameters.)
Then you can step recursively through the display list triggering clicks:
testClicks(loader.content as DisplayObjectContainer);
function testClicks(target:DisplayObjectContainer):void {
var numC:uint = target.numChildren;
for (var i:uint = 0; i < numC; i++) {
target.getChildAt(i).dispatchEvent(new MouseEvent(MouseEvent.CLICK));
if (target.getChildAt(i) is DisplayObjectContainer) {
testClicks(target.getChildAt(i) as DisplayObjectContainer);
}
}
}
If you set the folder with your test ad as trusted, or use the debug player, you'll be able to see if any of those clicks cause the ad to open a URL.
It's probably worth triggering MOUSE_DOWN and MOUSE_UP too in case the developer has used those instead, and obviously this won't reveal problems like very small click areas as jdangu mentions, but hopefully it's useful as a basic test.
You can use a clicktag checker like www.adbannerking.com It will reveal the clicktag that is in the SWF file. The software even allows you to change the clicktag accordingly without the need of the source files (.fla). At the same time you can check / change x amount of SWF files at the same time quickly.

Upload file programmatically

Can I programmatically upload a file to the server (without client's interference) ? I know this is not possible in normal (.html) files. Is there anyway I can do it from .hta file? or any server side or plug-gin solution?
from an HTA, you can use the shell object to run commands just as if you were running from the command line - including FTP - but of course you'll need FTP credentials. since you said you'll be able to hardcode the files to be uploaded, i assume you have full access...
var shell = new ActiveXObject('wscript.shell');
var params = // this should be a string of ftp commands, like OPEN ftp.example.com USER PASS CWD somedir PUT c:\whatever.txt BYE
shell.run("%comspec% /c ftp.exe -i -s:" + params, 1, true);
Short answer is no.
It may be possible on some machines using a signed java applet - but from the wording of the question, that's going to be a very long juorney for you.
Based on your last comment, you might atleast need the user to load a web page. So based on an onload function, you can use an ajax hidden form to submit whatever files that you'd want to.
But getting information from your user without their knowledge might put you in a legal situation.
Good luck!!

Categories