Repository: anam-hossain/phantommagick
Branch: master
Commit: 7da1cb921987
Files: 18
Total size: 49.4 KB
Directory structure:
gitextract_exfyuc5j/
├── .gitignore
├── README.md
├── composer.json
├── phpunit.xml.dist
├── src/
│ ├── Adapter.php
│ ├── Converter.php
│ ├── ConverterServiceProvider.php
│ ├── Exception/
│ │ ├── FileFormatNotSupportedException.php
│ │ └── FileNotFoundException.php
│ ├── Facades/
│ │ └── Converter.php
│ ├── Runner.php
│ ├── Str.php
│ └── scripts/
│ └── phantom_magick.js
└── tests/
├── AdapterTest.php
├── ConverterTest.php
├── PrivateAndProtectedMethodsAccessibleTrait.php
├── RunnerTest.php
└── test_page.html
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
.editorconfig
.env.php
/build
/vendor
/bin
================================================
FILE: README.md
================================================
# PhantomMagick
### For PhantomMagick version 1, please use the [1.0.2 branch](https://github.com/anam-hossain/phantommagick/tree/1.0.2)!
PhantomMagick provides a simple API to ease the process of converting HTML to PDF or images. It's especially handy for things like generating invoices or capturing screenshots of websites. It's framework agnostic but it does provide a facade for simple use in Laravel 4/5.
## Features
- Convert HTML to a PDF
- Convert HTML to an image (PNG, JPG or GIF)
- Support multipage PDFs
- Capture a web page as a screenshot
- Save PDF or image to local disk or to the cloud (S3, Dropbox or Rackspace)
- Framework agnostic, with optional Laravel integration
## Requirements
- PHP 5.5+
- [PhantomJS](http://phantomjs.org)
## Installation
PhantomMagick is available via Composer:
```bash
$ composer require anam/phantommagick
```
## Dependencies
[PhantomJS](http://phantomjs.org/download.html) must be installed to use PhantomMagick.
There are few ways to install PhantomJS:
##### Install binary manually
You can download the official PhantomJS binary from the following link:
[http://phantomjs.org/download.html](http://phantomjs.org/download.html).
##### Install binary through Composer
Simply pull in the `anam/phantomjs-linux-x86-binary` package to get the up-to-date PhantomJS binary for 64-bit Linux systems.
```bash
composer require anam/phantomjs-linux-x86-binary
```
## Integrations
##### Laravel 4 and Laravel 5 integrations
Although `PhantomMagick` is framework agnostic, it does support Laravel out of the box and comes with a Service provider and Facade for easy integration.
After you have installed the PhantomMagick, open the `config/app.php` file which is included with Laravel and add the following lines.
In the `$providers` array add the following service provider.
```php
'Anam\PhantomMagick\ConverterServiceProvider'
```
Add the facade of this package to the `$aliases` array.
```php
'Converter' => 'Anam\PhantomMagick\Facades\Converter'
```
You can now use this facade in place of instantiating the converter yourself in the following examples.
## Usage
### PDF conversion
```php
$conv = new \Anam\PhantomMagick\Converter();
$conv->source('http://google.com')
->toPdf()
->save('/your/destination/path/google.pdf');
```
##### Multipage PDFs
```php
use Anam\PhantomMagick\Converter;
$conv = new Converter();
$conv->addPage('<html><body><h1>Welcome to PhantomMagick</h1></body></html>')
->addPage('http://facebook.com')
->addPage('/html/file/from/local/drive/example.html')
->save('/your/destination/path/multipage.pdf');
```
Please note with multipage PDFs:
- Only absolute paths are supported, so avoid relative paths
- Inline styles or inline style stylesheets are recommended
### Image conversion
PhantomMagick supports HTML to PNG/JPG/GIF conversion.
```php
$conv = new \Anam\PhantomMagick\Converter();
$conv->source('http://google.com')
->toPng()
->save('/your/destination/path/google.png');
```
###### HTML to PNG
```php
$conv->toPng()
```
###### HTML to JPG
```php
$conv->toJpg()
```
###### HTML to GIF
```php
$conv->toGif()
```
### Download file
```php
use Anam\PhantomMagick\Converter;
Converter::make('http://google.com')
->toPdf()
->download('google.pdf');
Converter::make('http://yahoo.com')
->toPng()
->download('yahoo.png');
```
To display in the browser instead of forcing the file to be download, you can pass a second parameter to the method.
```php
$conv->download('google.pdf', true);
```
or just simply call:
```php
$conv->serve();
```
## Save to cloud
PhantomMagick leverages [Flysystem](http://flysystem.thephpleague.com) to save converted files in the cloud.
PhantomMagick currently supports:
- Amazon S3
- Dropbox
- Rackspace
##### Amazon S3
First install the required S3 dependencies through Composer.
```bash
composer require aws/aws-sdk-php
composer require league/flysystem-aws-s3-v3
```
```php
use Anam\PhantomMagick\Converter;
use Aws\S3\S3Client;
$client = S3Client::factory([
'credentials' => [
'key' => 'AWS_KEY',
'secret' => 'AWS_SECRET',
],
'region' => 'your-region',
'version' => 'latest',
]);
$conv = new Converter();
$conv->adapter($client, 'bucket-name', 'optional/path/prefix')
->acl('public')
->source('http://google.com')
->toPdf()
->save('google.pdf');
```
##### Dropbox
First install the required Dropbox dependencies through Composer.
```bash
composer require dropox/dropbox-sdk
composer require flysystem-dropbox
```
```php
use Anam\PhantomMagick\Converter;
use Dropbox\Client;
$client = new Client('DROPBOX_TOKEN', 'DROPBOX_APP');
$conv = new Converter();
$conv->adapter($client)
->source('https://google.com')
->toPdf()
->save('dropbox_example.pdf');
```
##### Rackspace
First install the required Rackspace dependencies through Composer.
```bash
composer require rackspace/php-opencloud
composer require league/flysystem-rackspace
```
```php
use Anam\PhantomMagick\Converter;
use OpenCloud\OpenStack;
use OpenCloud\Rackspace;
$client = new OpenStack(Rackspace::US_IDENTITY_ENDPOINT, array(
'username' => 'RACKSPACE_USERNAME',
'password' => 'RACKSPACE_PASSWORD'
));
$store = $client->objectStoreService('cloudFiles', 'SYD');
$container = $store->getContainer('phantom-magick');
$conv = new Converter();
$conv->adapter($container)
->source('https://google.com')
->toPdf()
->save('rackspace_example.pdf');
```
### Settings
#### Global options
###### Binary
You can set the path of the `phantomjs` binary if you've installed it yourself manually, or the `phantomjs` command is not available in your shell. If you installed it through Composer (with the `anam/phantomjs-linux-x86-binary` package) PhantomMagick will be smart enough to find the file automatically.
```php
$conv->setBinary('/phantomjs/binary/path/phantomjs');
```
###### Data Source
PhantomMagick only supports HTML and data can be provided via an URL or from the local disk. If you need to use raw HTML data, you can use multipage PDF conversion. However raw data does have some limitations; it does not support relative paths and it only supports inline styles and internal CSS.
```php
new Converter('/Path/to/file/example.html');
// or
Converter::make('/Path/to/file/example.html');
//or
$conv->source('/Path/to/file/example.html');
// or
$conv->source('http://google.com');
```
For raw HTML:
```php
$conv->addPage('<html><body><h1>Raw HTML</h1></body></html>');
```
#### PDF options
###### Format
Format is optional. Supported formats are: 'A3', 'A4', 'A5', 'Legal', 'Letter', 'Tabloid'.
```php
$conv->format('A4');
```
###### Margin
Margin is optional and defaults to 1cm.
```php
array('margin' => '1cm')
```
###### Orientation
Orientation ('portrait', 'landscape') is optional and defaults to 'portrait'.
```php
$conv->portrait();
$conv->landscape();
```
###### zoomFactor
zoomFactor is optional and defaults to 1 (where 1 is 100% zoom).
```php
array('zoomfactor' => 1)
```
###### Custom width and height
Custom dimension is optional. Supported formats are `cm`, `px` and `in`.
```php
array('width' => '900px', height => '700px')
```
##### Example
```php
$options = [
'format' => 'A4',
'zoomfactor' => 1,
'orientation' => 'portrait',
'margin' => '1cm'
];
$conv->setPdfOptions($options);
// or
$conv->pdfOptions($options);
// or
$conv->toPdf($options);
```
#### Image options
###### Width
Width is optional and defaults to 1280px (720p) and only intergers are accepted.
```php
$conv->width(1280);
```
###### Height
Height is optional and only integers are accepted.
```php
$conv->height(1280);
```
**Note:** If only width is given full webpage will be rendered. However, if both width and height is given the image will be clipped to the given width and height.
###### Quality
Quality is optional and defaults to 80. The quality must be between 1-100.
```php
$conv->quality(90);
```
#####Example
```php
$options = [
'width' => 1280,
'quality' => 90
];
$conv->setImageOptions($options);
// or
$conv->imageOptions($options);
// or
$conv->toPng($options);
// or
$conv->toJpg($options);
// or
$conv->toGif($options);
```
## Credits
- [Anam Hossain](https://github.com/anam-hossain)
- [All Contributors](https://github.com/anam-hossain/phantommagick/graphs/contributors)
## License
The MIT License (MIT). Please see [LICENSE](http://opensource.org/licenses/MIT) for more information.
================================================
FILE: composer.json
================================================
{
"name": "anam/phantommagick",
"description": "PhantomMagick provides a simple API to ease the process of converting HTML to PDF or images",
"keywords": [
"Pdf",
"Html to pdf",
"html to image",
"Html 2 pdf",
"Html 2 jpg",
"html to png",
"Screen capture",
"invoice",
"Laravel pdf",
"Laravel",
"Phantomjs",
"pdf converter",
"image converter",
"converter",
"Phantom"
],
"homepage": "https://github.com/anam-hossain/phantommagick",
"license": "MIT",
"authors": [
{
"name": "Anam hossain",
"email": "enam33@gmail.com"
}
],
"require": {
"php": ">=5.4.0",
"league/flysystem": "~1.0"
},
"require-dev": {
"mockery/mockery": "~0.9",
"phpunit/phpunit": "~4.4"
},
"autoload": {
"psr-4": {
"Anam\\PhantomMagick\\" : "src/"
}
},
"autoload-dev": {
"psr-4": {
"Anam\\PhantomMagick\\Test\\": "tests"
}
}
}
================================================
FILE: phpunit.xml.dist
================================================
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnError="false"
stopOnFailure="false"
bootstrap="vendor/autoload.php">
<testsuites>
<testsuite name="all">
<directory suffix="Test.php">tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
<logging>
<log type="tap" target="build/report.tap"/>
<log type="junit" target="build/report.junit.xml"/>
<log type="coverage-html" target="build/coverage" charset="UTF-8" yui="true" highlight="true"/>
<log type="coverage-text" target="build/coverage.txt"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
</logging>
</phpunit>
================================================
FILE: src/Adapter.php
================================================
<?php
namespace Anam\PhantomMagick;
use Exception;
use InvalidArgumentException;
class Adapter
{
/**
* The driver of the Filesystem
*
* @var string
*/
protected $driver = 'local';
/**
* Filesystem client. S3|Dropbox|Rackspace.
*
* @var mixed
*/
protected $client;
/**
* Client related options
*
* @var array
*/
protected $args;
/**
* Constructor
*
* @param mixed $client
* @param array $args
*/
public function __construct($client, array $args = [])
{
$this->client = $client;
$this->args = $args;
}
/**
* Set the Filesystem driver
*
* @param string $driver
*/
public function setDriver($driver)
{
$this->driver = $driver;
}
/**
* Get the driver
*
* @return string
*/
public function getDriver()
{
return $this->driver;
}
/**
* Determine which Flysystem adapter required
*
* @return mixed
*/
public function pick()
{
// Amazon S3
if ($this->client instanceof \Aws\S3\S3Client) {
$this->setDriver('s3');
return $this->s3();
}
// Dropbox
if ($this->client instanceof \Dropbox\Client) {
$this->setDriver('dropbox');
return $this->dropbox();
}
// Rackspace cloudFiles
if ($this->client instanceof \OpenCloud\ObjectStore\Resource\Container) {
$this->setDriver('rackspace');
return $this->rackspace();
}
}
/**
* Create a new AwsS3Adapter instance.
*
* @return mixed
*/
public function s3()
{
$pathPrefix = '';
if (! isset($this->args[0])) {
throw new InvalidArgumentException('S3 Bucket name is required');
}
$bucket = $this->args[0];
if (isset($this->args[1]) && $this->args[1]) {
$pathPrefix = $this->args[1];
}
return new \League\Flysystem\AwsS3v3\AwsS3Adapter($this->client, $bucket, $pathPrefix);
}
/**
* Create a new DropboxAdapter instance.
*
* @return \League\Flysystem\Dropbox\DropboxAdapter
*/
public function dropbox()
{
$prefix = null;
if (isset($this->args[0])) {
$prefix = $this->args[0];
}
return new \League\Flysystem\Dropbox\DropboxAdapter($this->client, $prefix);
}
/**
* Create a new RackspaceAdapter instance.
*
* @return \League\Flysystem\Rackspace\RackspaceAdapter
*/
public function rackspace()
{
return new \League\Flysystem\Rackspace\RackspaceAdapter($this->client);
}
}
================================================
FILE: src/Converter.php
================================================
<?php
namespace Anam\PhantomMagick;
use Exception;
use RuntimeException;
use InvalidArgumentException;
use Anam\PhantomMagick\Exception\FileFormatNotSupportedException;
use Anam\PhantomMagick\Adapter;
use League\Flysystem\Filesystem;
class Converter extends Runner
{
/**
* The driver of the Filesystem
*
* @var string
*/
protected $driver = 'local';
/**
* The visibily of the file
*
* @var string
*/
protected $acl = 'private';
/**
* The Filesystem instance.
*
* @var \League\Flysystem\Filesystem $filesystem
*/
protected $filesystem;
/**
* The temporary directory path
*
* @var string
*/
protected $tempFilePath;
/**
* The source of the html data.
* Source might be the physical file path or URL.
*
* @var string
*/
protected $source;
/**
* The output file format
*
* @var string
*/
private static $format = 'pdf';
/**
* Multiple HTML pages.
*
* @var array
*/
protected $pages = [];
/**
* Indicates if the conversion is multi pages or not.
*
* @var boolean
*/
protected static $multiPage = false;
/**
* The conversion scripts.
*
* @var array
*/
protected static $scripts = [];
/**
* Default PDF settings
*
* @var array
*/
protected static $pdfOptions = [
//Supported formats are: 'A3', 'A4', 'A5', 'Legal', 'Letter', 'Tabloid'
'format' => 'A4',
// 1 = 100% zoom
'zoomfactor' => 1,
'quality' => '70',
//Orientation: 'portrait', 'landscape'
'orientation' => 'portrait',
'margin' => '1cm'
];
/**
* Default Image settings
*
* @var array
*/
protected static $imageOptions = [
// Dimension in pixels.
// if only width is given full webpage will render
// if both width and height is given,
// the image will be clipped to given width and height
'dimension' => '1280px',
// 1 = 100% zoom
'zoomfactor' => 1,
'quality' => '80'
];
/**
* Supported image formats
*
* @var array
*/
protected static $imageFormats = [
'png' => '.png',
'jpg' => '.jpg',
'gif' => '.gif'
];
/**
* Supported Paper sizes.
* Only use in PDF conversion
*
* @var array
*/
protected static $paperSizes = [
'A3',
'A4',
'A5',
'Legal',
'Letter',
'Tabloid'
];
/**
* Initialize the Converter
*
* @param string $source source of the data file
*/
public function __construct($source = null)
{
$this->initialize();
if ($source) {
$this->setSource($source);
}
parent::__construct();
}
/**
* Initialize the converter settings
*
* @return void
*/
private function initialize()
{
self::$scripts['converter'] = dirname(__FILE__) . '/scripts/phantom_magick.js';
}
/**
* Create a new Converter instance.
*
* @param string $source Source of the data file
* @return Converter
*/
public static function make($source)
{
return new self($source);
}
/**
* Pick appropriate Flysystem adapter for a client
*
* @param mixed $client
* @return $this
*/
public function adapter($client)
{
$args = func_get_args();
array_shift($args);
$adapter = new Adapter($client, $args);
$this->filesystem = new Filesystem($adapter->pick());
$this->driver = $adapter->getDriver();
return $this;
}
/**
* Set visibility
*
* @param string $acl
* @return $this
*/
public function acl($acl)
{
$this->acl = $acl;
return $this;
}
/**
* Set PhantomJS binary location
*
* @param string $binary phantomsjs location
* @return $this
**/
public function setBinary($binary)
{
$this->binary = $binary;
return $this;
}
/**
* Get the Executable PhantomJS binary source
*
* @return string
*/
public function getBinary()
{
return $this->binary;
}
/**
* Get the driver of the filesystem
*
* @return string
*/
public function getDriver()
{
return $this->driver;
}
/**
* Set the temporary file path
*
* @param string $filename
* @return void
*/
public function setTempFilePath($filename)
{
$this->tempFilePath = $filename;
}
/**
* Get the temporary file location
*
* @return string
*/
public function getTempFilePath()
{
return $this->tempFilePath;
}
/**
* Get the conversion scripts
*
* @return array
*/
public function getScript()
{
return self::$scripts['converter'];
}
/**
* Set the data source
*
* @param string $source
* @return $this
*/
public function setSource($source)
{
$this->source = $source;
return $this;
}
/**
* Get the data source
*
* @return string
*/
public function getSource()
{
return $this->source;
}
/**
* Alias of the setSource()
*
* @param string $source
* @return string
*/
public function source($source)
{
return $this->setSource($source);
}
/**
* Prepare converter for pdf conversion
*
* @param array $options PDF settings
* @return $this
*/
public function toPdf(array $options = [])
{
$this->pdfOptions($options);
$this->setTempFilePath(sys_get_temp_dir() . '/' . uniqid(rand()) . '.pdf');
return $this;
}
/**
* Prepare converter for PNG conversion
*
* @param array $options Image settings
* @return $this
*/
public function toPng(array $options = [])
{
return $this->prepareImage($options, $format = 'png');
}
/**
* Prepare converter for JPG conversion
*
* @param array $options Image settings
* @return $this
*/
public function toJpg(array $options = [])
{
return $this->prepareImage($options, $format = 'jpg');
}
/**
* Prepare converter for GIF conversion
*
* @param array $options Image settings
* @return $this
*/
public function toGif(array $options = [])
{
return $this->prepareImage($options, $format = 'gif');
}
/**
* Prepare converter for Image conversion
*
* @param array $options Image settings
* @param string $format Image format JPG|PNG|GIF
*
* @return $this
*/
public function toImage($options, $format = 'png')
{
return $this->prepareImage($options, $format);
}
/**
* Prepare converter for Image conversion
*
* @param array $options Image settings
* @param string $format Image format JPG|PNG|GIF
*
* @return $this
*/
public function prepareImage($options, $format = 'png')
{
$format = strtolower($format);
if (! array_key_exists($format, self::$imageFormats)) {
throw new FileFormatNotSupportedException("{$format} file format not Supported.");
}
self::$format = $format;
$this->imageOptions($options);
$this->setTempFilePath(sys_get_temp_dir() . '/' . uniqid(rand()) . self::$imageFormats[$format]);
return $this;
}
/**
* Add HTMl page
*
* @param string $page Data file path|URL|Raw html code
*/
public function addPage($page)
{
self::$multiPage = true;
if (count($this->pages)) {
$this->pageBreak();
}
$this->pushContent($page);
return $this;
}
/**
* Add multiple pages
*
* @param array $pages Data files paths|URLs|Raw HTML code
* @return $this
*/
public function addPages(array $pages)
{
self::$multiPage = true;
foreach ($pages as $page) {
if (count($this->pages)) {
$this->pageBreak();
}
$this->pushContent($page);
}
return $this;
}
/**
* Push data to pages
*
* @param string $page file path|URL|Raw HTML
* @return void
*/
public function pushContent($page)
{
// @file_get_contents will not throw any exception due to @ symbol
// file_get_contents will try to load file from physical path or from an URL
// and will return the content as string
// If failed, it will return false.
$content = @file_get_contents($page);
// Perhaps raw HTML content.
if (! $content) {
$content = $page;
}
array_push($this->pages, $content);
}
/**
* Get pages
*
* @return array
*/
public function getPages()
{
return $this->pages;
}
/**
* Add page break to pages
*
* @return void
*/
public function pageBreak()
{
$content = '<div style="page-break-after:always;"><!-- page break --></div>';
array_push($this->pages, $content);
}
/**
* Add contents to the tempfile file.
*
* @param string $content
* @return void
*/
protected function put($content)
{
$this->createTempFile();
file_put_contents($this->getTempFilePath(), $content, FILE_APPEND);
}
/**
* Create a temporary html file for converting mutipages pdf
*
* @return string
*/
protected function createTempFile()
{
$this->setTempFilePath(sys_get_temp_dir() . '/' . uniqid(rand()) . '.html');
if (! touch($this->getTempFilePath())) {
throw new RuntimeException('Unable to create file in temp directory: '. sys_get_temp_dir());
}
return $this->getTempFilePath();
}
/**
* Force download file when conversion is completed
*
* @param string $downloadAs filename
* @param boolean $inline Show file in browser or not
* @return void
*/
public function download($downloadAs = null, $inline = false)
{
// Force "local" driver.
$this->driver = 'local';
$filename = $this->getTempFilePath();
if (self::$multiPage) {
$this->put(implode('', $this->pages));
$this->resetPages();
$filename = dirname($this->getTempFilePath()) . "/" . basename($this->getTempFilePath(), ".html") . ".pdf";
}
$result = $this->save($filename);
// Log warning or errors using PHP system logger
if (trim($result)) {
error_log($result);
}
$pathParts = pathinfo($filename);
$downloadAs = $downloadAs? $downloadAs : $pathParts['basename'];
$contentDisposition = $inline? 'inline' : 'attachment';
$contentType = $this->contentType($pathParts['extension']);
if (! file_exists($filename)) {
error_log("Conversion failed.");
return "Conversion failed.";
}
header('Content-Description: File Transfer');
header("Content-Type: {$contentType}");
header("Content-Disposition: {$contentDisposition}; filename={$downloadAs}");
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
readfile($filename);
unlink($filename);
$this->clearTempFiles();
exit;
}
/**
* Download and display the file in browser
*
* @return void
*/
public function serve()
{
$this->download(null, true);
}
/**
* Save PDF|Image to the given file path if driver is local.
* or Save file in cloud with provided filename
*
* @param string $filename full physical path with filename for local driver or just filename for cloud.
* @return mixed
**/
public function save($filename = null)
{
if ($this->driver == 'local' && ! $filename) {
throw new InvalidArgumentException("Filename can not be empty. Please provide a full physical path with filename.");
}
if (! $filename) {
$pathParts = pathinfo($this->getSource());
$filename = $pathParts['filename'] . '.' . self::$format;
if (self::$multiPage) {
$filename = uniqid('phantom_magick') . '.' . self::$format;
}
}
if ($this->driver == 'local') {
return $this->saveLocal($filename);
}
return $this->saveCloud($filename);
}
/**
* Save PDF|Image to the given file path.
*
* @param string $filename full physical path with filename
* @return mixed
**/
public function saveLocal($filename)
{
if (self::$multiPage) {
if (count($this->pages)) {
$this->put(implode('', $this->pages));
}
return $this->run(self::$scripts['converter'], $this->getTempFilePath(), $filename, self::$pdfOptions);
}
// Single page pdf
if (self::$format === 'pdf') {
return $this->run(self::$scripts['converter'], $this->getSource(), $filename, self::$pdfOptions);
}
// Image
return $this->run(self::$scripts['converter'], $this->getSource(), $filename, self::$imageOptions);
}
/**
* Save PDF|Image to the cloud.
*
* @param string $filename.
* @return mixed
**/
public function saveCloud($filename)
{
$tempFilename = $this->getTempFilePath();
// Multi page pdf
if (self::$multiPage) {
if (count($this->pages)) {
$this->put(implode('', $this->pages));
}
$tempFilename = dirname($this->getTempFilePath()) . "/" . basename($this->getTempFilePath(), ".html") . ".pdf";
$this->run(self::$scripts['converter'], $this->getTempFilePath(), $tempFilename, self::$pdfOptions);
} elseif (self::$format === 'pdf') {
$this->run(self::$scripts['converter'], $this->getSource(), $tempFilename, self::$pdfOptions);
} else {
$this->run(self::$scripts['converter'], $this->getSource(), $tempFilename, self::$imageOptions);
}
if (file_exists($tempFilename)) {
$contents = file_get_contents($tempFilename);
unlink($tempFilename);
return $this->filesystem->put($filename, $contents, ['visibility' => $this->acl]);
}
}
/**
* Set the PDF options
*
* @param array $options
* @return $this
*/
public function setPdfOptions(array $options)
{
$this->pdfOptions($options);
return $this;
}
/**
* Get PDF options
*
* @return $array
*/
public function getPdfOptions()
{
return self::$pdfOptions;
}
/**
* Update PDF settings
*
* @param array $options
* @return $this
*/
public function pdfOptions(array $options)
{
foreach ($options as $key => $option) {
if (isset(self::$pdfOptions[$key])) {
self::$pdfOptions[$key] = $option;
}
}
// Custom paper width and height will replace the default format.
if (isset($options['width']) && isset($options['height'])) {
// ex. 10cm*5cm, 1200px*1000px, 10in*5in, 900*600
// note: without unit (i.e 900*600) will use px.
self::$pdfOptions['format'] = $options['width'] . '*' . $options['height'];
}
return $this;
}
/**
* Set the Image options
*
* @param array $options
* @return $this
*/
public function setImageOptions(array $options)
{
$this->imageOptions($options);
return $this;
}
/**
* Get Image settings
*
* @return $array
*/
public function getImageOptions()
{
return self::$imageOptions;
}
/**
* Update image settings
*
* @param array $options
* @return $this
*/
public function imageOptions(array $options)
{
foreach ($options as $key => $option) {
if (isset(self::$imageOptions[$key])) {
self::$imageOptions[$key] = $option;
}
}
if (isset($options['width']) && isset($options['height'])) {
// Only digits accepted
if (! ctype_digit($options['width'])) {
throw new Exception('Width must be a number');
}
if (! ctype_digit($options['height'])) {
throw new Exception('Height must be a number');
}
self::$imageOptions['dimension'] = $options['width'] . 'px' . '*' . $options['height'] . 'px';
} elseif (isset($options['width'])) {
if (! ctype_digit($options['width'])) {
throw new Exception('Width must be a number');
}
self::$imageOptions['dimension'] = $options['width'] . 'px';
}
return $this;
}
/**
* Set the Paper format for PDF conversion
* @return $this
*/
public function format($format)
{
if (! in_array($format, self::$paperSizes)) {
throw new Exception('Paper format not supported.');
}
self::$pdfOptions['format'] = $format;
return $this;
}
/**
* Set the Portrait orientation
* Only use in PDF conversion
* @return $this
*/
public function portrait()
{
self::$pdfOptions['orientation'] = 'portrait';
return $this;
}
/**
* Set the Landscape orientation
* Only use in PDF conversion
* @return $this
*/
public function landscape()
{
self::$pdfOptions['orientation'] = 'landscape';
return $this;
}
/**
* Set the Width
* Only use in Image conversion
* @return $this
*/
public function width($width)
{
if (! ctype_digit($width)) {
throw new Exception('Width must be a number');
}
$dimension = explode("*", self::$imageOptions['dimension']);
$dimension[0] = $width . 'px';
self::$imageOptions['dimension'] = implode("*", $dimension);
return $this;
}
/**
* Set the Height
* Only use in Image conversion
* @return $this
*/
public function height($height)
{
if (! ctype_digit($height)) {
throw new Exception('Height must be a number');
}
$dimension = explode("*", self::$imageOptions['dimension']);
$dimension[1] = $height . 'px';
self::$imageOptions['dimension'] = implode("*", $dimension);
return $this;
}
/**
* Set the Image quality
* Only used in Image conversion
* @return $this
*/
public function quality($quality = 80)
{
if (! ($quality >=1 && $quality <=100)) {
throw new Exception('Quality must be between 1-100');
}
self::$imageOptions['quality'] = $quality;
return $this;
}
/**
* Determine file mime
*
* @param string $ext
* @return string
*/
public function contentType($ext)
{
switch ($ext) {
case 'pdf':
return 'application/pdf';
case 'jpg':
return 'image/jpeg';
case 'png':
return 'image/png';
case 'gif':
return 'image/gif';
default:
return 'application/pdf';
}
}
/**
* Reset pages
* @return void
*/
public function resetPages()
{
$this->pages = [];
}
/**
* Remove temporary files
*
* @return void
*/
public function clearTempFiles()
{
if (file_exists($this->getTempFilePath())) {
unlink($this->getTempFilePath());
}
}
public function __destruct()
{
$this->clearTempFiles();
}
}
================================================
FILE: src/ConverterServiceProvider.php
================================================
<?php
namespace Anam\PhantomMagick;
use Illuminate\Support\ServiceProvider;
class ConverterServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('converter', function() {
return new \Anam\PhantomMagick\Converter;
});
}
}
================================================
FILE: src/Exception/FileFormatNotSupportedException.php
================================================
<?php
namespace Anam\Html2PdfConverter\Exception;
use Exception;
class FileFormatNotSupportedException extends Exception
{
}
================================================
FILE: src/Exception/FileNotFoundException.php
================================================
<?php
namespace Anam\Html2PdfConverter\Exception;
use Exception;
class FileNotFoundException extends Exception
{
}
================================================
FILE: src/Facades/Converter.php
================================================
<?php
namespace Anam\PhantomMagick\Facades;
use Illuminate\Support\Facades\Facade;
class Converter extends Facade
{
protected static function getFacadeAccessor() { return 'converter'; }
}
================================================
FILE: src/Runner.php
================================================
<?php
namespace Anam\PhantomMagick;
use Exception;
use Anam\PhantomMagick\Str;
class Runner
{
/**
* Executable phantomjs binary path
*
* @var string
*/
protected $binary = 'phantomjs';
/**
* Executable phantomjs binary path
*
* @var string
*/
protected $alternateBinary;
/**
* Phantomjs command with arguments
*
* @var string
*/
protected $command;
/**
* Constructor
*
* @param string $binary
*/
public function __construct($binary = null)
{
if ($binary !== null) {
$this->binary = $binary;
}
if (class_exists('\Anam\PhantomLinux\Path')) {
$this->setAlternateBinary(\Anam\PhantomLinux\Path::binaryPath());
}
}
/**
* Set Alternate Binary
*
* @param string $binary
*
* @return void
**/
public function setAlternateBinary($binary)
{
$this->alternateBinary = $binary;
}
/**
* Get Alternate binary
*
* @return string
**/
public function getAlternateBinary()
{
return $this->alternateBinary;
}
/**
* Set shell command
*
* @param string $command
*
* @return void
**/
public function setCommand($command)
{
$this->command = $command;
}
/**
* Get PhantomJS shell command
*
* @return string
**/
public function getCommand()
{
return $this->command;
}
/**
* Run the phantomjs command
* @param string $script Conversion script
* @param string $source Data file location
* @param string $output Output file location
* @param array $options
* @return string
*/
public function run($script, $source, $output, array $options = array())
{
$binary = $this->pickBinary();
$arguments = ['script' => $script, 'source' => $source, 'output' => $output] + $options;
$arguments = $this->escapeShellArguments($arguments);
$this->setCommand(escapeshellcmd("{$binary} --ssl-protocol=any --ignore-ssl-errors=yes ") . implode(' ', $arguments));
return shell_exec($this->getCommand());
}
/**
* Escape shell arguments
*
* @param array $arguments
* @return array
*/
private function escapeShellArguments(array $arguments)
{
foreach ($arguments as $key => $argument) {
$arguments[$key] = escapeshellarg($argument);
}
return $arguments;
}
/**
* Check phantomjs is installed or not
*
* @param string $binary Binary location
* @return boolean
*/
public function verifyBinary($binary)
{
$uname = strtolower(php_uname());
if (Str::contains($uname, 'darwin')) {
if (! shell_exec(escapeshellcmd("command -v {$binary} >/dev/null 2>&1"))) {
return false;
}
} elseif (Str::contains($uname, 'win')) {
if (! shell_exec(escapeshellcmd("{$binary}"))) {
return false;
}
} elseif (Str::contains($uname, 'linux')) {
if (! shell_exec(escapeshellcmd("which {$binary}"))) {
return false;
}
} else {
throw new \RuntimeException("Unknown operating system.");
}
return true;
}
/**
* Choose binary
*
* @return string
*/
public function pickBinary()
{
if ($this->binary != 'phantomjs') {
if (! $this->verifyBinary($this->binary)) {
throw new Exception('Binary does not exist');
}
return $this->binary;
}
if (! $this->verifyBinary($this->binary)) {
if (! $this->verifyBinary($this->getAlternateBinary())) {
throw new Exception('Binary does not exist');
}
$this->binary = $this->getAlternateBinary();
}
return $this->binary;
}
}
================================================
FILE: src/Str.php
================================================
<?php
namespace Anam\PhantomMagick;
class Str
{
/**
* This method is the part of illuminate/support package.
* visit: https://github.com/illuminate/support for more info.
*
* Determine if a given string contains a given substring.
*
* @param string $haystack
* @param string|array $needles
* @return bool
*/
public static function contains($haystack, $needles)
{
foreach ((array) $needles as $needle) {
if ($needle != '' && strpos($haystack, $needle) !== false) {
return true;
}
}
return false;
}
}
================================================
FILE: src/scripts/phantom_magick.js
================================================
var page = require('webpage').create(),
system = require('system'),
quality = system.args[5] || '70',
orientation = system.args[6] || 'portrait',
margin = system.args[7] || '1cm',
address, output, size;
if (system.args.length < 3 || system.args.length > 8) {
console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom] [orientation] [margin] [quality]');
console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"');
console.log(' image (png/jpg output) examples: "1920px" entire page, window width 1920px');
console.log(' "800px*600px" window, clipped to 800x600');
phantom.exit(1);
} else {
address = system.args[1];
output = system.args[2];
page.viewportSize = { width: 1280, height: 720 };
if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") {
size = system.args[3].split('*');
page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: margin }
: { format: system.args[3], orientation: orientation, margin: margin };
} else if (system.args.length > 3 && system.args[3].substr(-2) === "px") {
size = system.args[3].split('*');
if (size.length === 2) {
pageWidth = parseInt(size[0], 10);
pageHeight = parseInt(size[1], 10);
page.viewportSize = { width: pageWidth, height: pageHeight };
page.clipRect = { top: 0, left: 0, width: pageWidth, height: pageHeight };
} else {
// If a number received, instead of width and height,
// Try to use best width and height by inspecting the number.
console.log("size:", system.args[3]);
pageWidth = parseInt(system.args[3], 10);
pageHeight = parseInt(pageWidth * 3/4, 10); // it's as good an assumption as any
console.log ("pageHeight:",pageHeight);
page.viewportSize = { width: pageWidth, height: pageHeight };
}
}
if (system.args.length > 4) {
page.zoomFactor = system.args[4];
}
// Add better error reporting when url fails to load.
page.onResourceError = function(resourceError) {
page.reason = resourceError.errorString;
page.reason_url = resourceError.url;
};
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
console.log(
"Error opening url \"" + page.reason_url
+ "\": " + page.reason
);
phantom.exit(1);
} else {
window.setTimeout(function () {
page.render(output, {quality: quality});
phantom.exit();
}, 200);
}
});
}
================================================
FILE: tests/AdapterTest.php
================================================
<?php
namespace Anam\PhantomMagick\Test;
use Exception;
use RuntimeException;
use InvalidArgumentException;
use Anam\PhantomMagick\Adapter;
class AdapterTest extends \PHPUnit_Framework_TestCase
{
protected $adapter;
public function setUp()
{
}
/**
* @expectedException InvalidArgumentException
*/
public function testAmazonS3AdapterWillThrowInvalidArgumentException()
{
throw new InvalidArgumentException("Bucket is required");
}
}
================================================
FILE: tests/ConverterTest.php
================================================
<?php
namespace Anam\PhantomMagick\Test;
use Exception;
use RuntimeException;
use Mockery;
use Anam\PhantomMagick\Converter;
use League\Flysystem\Filesystem;
use Anam\PhantomMagick\Adapter;
use Anam\PhantomMagick\Exception\FileFormatNotSupportedException;
use Aws\S3\S3Client;
class ConverterTest extends \PHPUnit_Framework_TestCase
{
use PrivateAndProtectedMethodsAccessibleTrait;
protected $converter;
protected $pdfOptions = [
'format' => 'A3',
'zoomfactor' => 2,
'quality' => '100',
'orientation' => 'landscape',
'margin' => '2cm'
];
protected $imageOptions = [
'dimension' => '1000px',
'zoomfactor' => 2,
'quality' => '90'
];
public function setUp()
{
$this->converter = new Converter();
}
public function testInitialize()
{
$this->invokeMethod($this->converter, 'initialize');
$this->assertContains('phantom_magick.js', $this->converter->getScript(), 'Verify that phantom_magick.js is used');
}
public function testMake()
{
$this->assertInstanceOf('Anam\PhantomMagick\Converter', Converter::make('http://code-chunk.com'), 'Check Converter::make() method returning the instance of \Anam\PhantomMagick\Converter');
}
public function testSetSource()
{
$this->converter->setSource('http://code-chunk.com');
$this->assertEquals('http://code-chunk.com', $this->converter->getSource());
}
public function testGetSource()
{
$this->converter->setSource('http://code-chunk.com');
$this->assertEquals('http://code-chunk.com', $this->converter->getSource());
}
public function testSource()
{
$this->converter->source('http://code-chunk.com');
$this->assertEquals('http://code-chunk.com', $this->converter->getSource());
}
public function testDefaultFileSystemDriverIsLocal()
{
$this->assertEquals('local', $this->converter->getDriver());
}
public function testFileSystemDriverIsS3WhenS3ClientIsUsedAsClient()
{
$client = S3Client::factory(array(
'key' => 'dummy-key-123',
'secret' => 'dummy-secret-123'
));
$this->converter->adapter($client, 'dummy-bucket');
$this->assertEquals('s3', $this->converter->getDriver());
}
public function testGetTempFilePath()
{
$path = '/dummy/file/path';
$this->converter->setTempFilePath($path);
$this->assertEquals($path, $this->converter->getTempFilePath());
}
public function testPdfOptions()
{
$this->converter->pdfOptions($this->pdfOptions);
$this->assertEquals($this->pdfOptions, $this->converter->getPdfOptions());
}
public function testImageOptions()
{
$options = [
'dimension' => '900px',
'zoomfactor' => 1,
];
$this->converter->imageOptions($options);
$this->assertArrayHasKey('quality', $this->converter->getImageOptions());
}
public function testContentType()
{
$mime = $this->converter->contentType('pdf');
$this->assertEquals('application/pdf', $mime);
}
public function testPagesIsEmpty()
{
$this->assertTrue(empty($this->converter->getPages()));
}
public function testPagesIsNotEmpty()
{
$this->converter->addPage('http://google.com');
$this->assertFalse(empty($this->converter->getPages()));
}
public function testPushContents()
{
$pages = ['<html><body><h1>Phantom magick</h1></body></html>'];
$this->converter->pushContent($pages[0]);
$this->assertEquals($pages, $this->converter->getPages());
}
public function testPageBreak()
{
$pages = [
'<html><body><h1>Phantom magick</h1></body></html>',
'<div style="page-break-after:always;"><!-- page break --></div>'
];
$this->converter->pushContent($pages[0]);
$this->converter->pageBreak();
$this->assertEquals($pages, $this->converter->getPages());
}
public function testAddPages()
{
$expected = [
'<html><body><h1>Page 1</h1></body></html>',
'<div style="page-break-after:always;"><!-- page break --></div>',
'<html><body><h1>Page 2</h1></body></html>',
];
$pages = [
'<html><body><h1>Page 1</h1></body></html>',
'<html><body><h1>Page 2</h1></body></html>'
];
$this->converter->addPages($pages);
$this->assertEquals($expected, $this->converter->getPages());
}
public function testToPdf()
{
$this->converter->toPdf($this->pdfOptions);
// Check pdf options is set properly
$this->assertEquals($this->pdfOptions, $this->converter->getPdfOptions());
// Check .pdf extension is set
$this->assertContains('.pdf', $this->converter->getTempFilePath());
}
public function testToPng()
{
$this->converter->toPng($this->imageOptions);
$this->assertEquals($this->imageOptions, $this->converter->getImageOptions());
// Check .png extension is set
$this->assertContains('.png', $this->converter->getTempFilePath());
}
public function testToJpg()
{
$this->converter->toJpg($this->imageOptions);
$this->assertEquals($this->imageOptions, $this->converter->getImageOptions());
// Check .png extension is set
$this->assertContains('.jpg', $this->converter->getTempFilePath());
}
public function testToGif()
{
$this->converter->toGif($this->imageOptions);
$this->assertEquals($this->imageOptions, $this->converter->getImageOptions());
// Check .png extension is set
$this->assertContains('.gif', $this->converter->getTempFilePath());
}
}
================================================
FILE: tests/PrivateAndProtectedMethodsAccessibleTrait.php
================================================
<?php
namespace Anam\PhantomMagick\Test;
trait PrivateAndProtectedMethodsAccessibleTrait
{
/**
* Call protected/private method of a class.
*
* @param object &$object Instantiated object that we will run method on.
* @param string $methodName Method name to call
* @param array $parameters Array of parameters to pass into method.
*
* @return mixed Method return.
*/
public function invokeMethod(&$object, $methodName, array $parameters = array())
{
$reflection = new \ReflectionClass(get_class($object));
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
}
================================================
FILE: tests/RunnerTest.php
================================================
<?php
namespace Anam\PhantomMagick\Test;
use Exception;
use RuntimeException;
use InvalidArgumentException;
use Anam\PhantomMagick\Runner;
class RunnerTest extends \PHPUnit_Framework_TestCase
{
protected $runner;
public function setUp()
{
$this->runner = new Runner();
}
/**
* Runner tests
*/
public function testVerifyBinary()
{
$this->assertTrue(true);
}
}
================================================
FILE: tests/test_page.html
================================================
<html>
<head>
<title>PhantomMagick</title>
</head>
<body>
<h1>Testing PhantomMagick</h1>
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
</body>
</html>
gitextract_exfyuc5j/
├── .gitignore
├── README.md
├── composer.json
├── phpunit.xml.dist
├── src/
│ ├── Adapter.php
│ ├── Converter.php
│ ├── ConverterServiceProvider.php
│ ├── Exception/
│ │ ├── FileFormatNotSupportedException.php
│ │ └── FileNotFoundException.php
│ ├── Facades/
│ │ └── Converter.php
│ ├── Runner.php
│ ├── Str.php
│ └── scripts/
│ └── phantom_magick.js
└── tests/
├── AdapterTest.php
├── ConverterTest.php
├── PrivateAndProtectedMethodsAccessibleTrait.php
├── RunnerTest.php
└── test_page.html
SYMBOL INDEX (105 symbols across 12 files)
FILE: src/Adapter.php
class Adapter (line 7) | class Adapter
method __construct (line 36) | public function __construct($client, array $args = [])
method setDriver (line 47) | public function setDriver($driver)
method getDriver (line 57) | public function getDriver()
method pick (line 67) | public function pick()
method s3 (line 96) | public function s3()
method dropbox (line 118) | public function dropbox()
method rackspace (line 134) | public function rackspace()
FILE: src/Converter.php
class Converter (line 11) | class Converter extends Runner
method __construct (line 140) | public function __construct($source = null)
method initialize (line 156) | private function initialize()
method make (line 167) | public static function make($source)
method adapter (line 178) | public function adapter($client)
method acl (line 199) | public function acl($acl)
method setBinary (line 212) | public function setBinary($binary)
method getBinary (line 225) | public function getBinary()
method getDriver (line 236) | public function getDriver()
method setTempFilePath (line 248) | public function setTempFilePath($filename)
method getTempFilePath (line 258) | public function getTempFilePath()
method getScript (line 268) | public function getScript()
method setSource (line 279) | public function setSource($source)
method getSource (line 291) | public function getSource()
method source (line 302) | public function source($source)
method toPdf (line 313) | public function toPdf(array $options = [])
method toPng (line 328) | public function toPng(array $options = [])
method toJpg (line 339) | public function toJpg(array $options = [])
method toGif (line 350) | public function toGif(array $options = [])
method toImage (line 363) | public function toImage($options, $format = 'png')
method prepareImage (line 377) | public function prepareImage($options, $format = 'png')
method addPage (line 399) | public function addPage($page)
method addPages (line 418) | public function addPages(array $pages)
method pushContent (line 439) | public function pushContent($page)
method getPages (line 461) | public function getPages()
method pageBreak (line 471) | public function pageBreak()
method put (line 484) | protected function put($content)
method createTempFile (line 496) | protected function createTempFile()
method download (line 514) | public function download($downloadAs = null, $inline = false)
method serve (line 566) | public function serve()
method save (line 579) | public function save($filename = null)
method saveLocal (line 607) | public function saveLocal($filename)
method saveCloud (line 632) | public function saveCloud($filename)
method setPdfOptions (line 667) | public function setPdfOptions(array $options)
method getPdfOptions (line 679) | public function getPdfOptions()
method pdfOptions (line 690) | public function pdfOptions(array $options)
method setImageOptions (line 714) | public function setImageOptions(array $options)
method getImageOptions (line 726) | public function getImageOptions()
method imageOptions (line 738) | public function imageOptions(array $options)
method format (line 772) | public function format($format)
method portrait (line 788) | public function portrait()
method landscape (line 800) | public function landscape()
method width (line 812) | public function width($width)
method height (line 832) | public function height($height)
method quality (line 852) | public function quality($quality = 80)
method contentType (line 869) | public function contentType($ext)
method resetPages (line 893) | public function resetPages()
method clearTempFiles (line 903) | public function clearTempFiles()
method __destruct (line 910) | public function __destruct()
FILE: src/ConverterServiceProvider.php
class ConverterServiceProvider (line 6) | class ConverterServiceProvider extends ServiceProvider
method register (line 8) | public function register()
FILE: src/Exception/FileFormatNotSupportedException.php
class FileFormatNotSupportedException (line 7) | class FileFormatNotSupportedException extends Exception
FILE: src/Exception/FileNotFoundException.php
class FileNotFoundException (line 7) | class FileNotFoundException extends Exception
FILE: src/Facades/Converter.php
class Converter (line 6) | class Converter extends Facade
method getFacadeAccessor (line 8) | protected static function getFacadeAccessor() { return 'converter'; }
FILE: src/Runner.php
class Runner (line 7) | class Runner
method __construct (line 35) | public function __construct($binary = null)
method setAlternateBinary (line 53) | public function setAlternateBinary($binary)
method getAlternateBinary (line 63) | public function getAlternateBinary()
method setCommand (line 75) | public function setCommand($command)
method getCommand (line 85) | public function getCommand()
method run (line 98) | public function run($script, $source, $output, array $options = array())
method escapeShellArguments (line 117) | private function escapeShellArguments(array $arguments)
method verifyBinary (line 132) | public function verifyBinary($binary)
method pickBinary (line 160) | public function pickBinary()
FILE: src/Str.php
class Str (line 4) | class Str
method contains (line 16) | public static function contains($haystack, $needles)
FILE: tests/AdapterTest.php
class AdapterTest (line 9) | class AdapterTest extends \PHPUnit_Framework_TestCase
method setUp (line 13) | public function setUp()
method testAmazonS3AdapterWillThrowInvalidArgumentException (line 21) | public function testAmazonS3AdapterWillThrowInvalidArgumentException()
FILE: tests/ConverterTest.php
class ConverterTest (line 13) | class ConverterTest extends \PHPUnit_Framework_TestCase
method setUp (line 34) | public function setUp()
method testInitialize (line 39) | public function testInitialize()
method testMake (line 46) | public function testMake()
method testSetSource (line 51) | public function testSetSource()
method testGetSource (line 58) | public function testGetSource()
method testSource (line 64) | public function testSource()
method testDefaultFileSystemDriverIsLocal (line 71) | public function testDefaultFileSystemDriverIsLocal()
method testFileSystemDriverIsS3WhenS3ClientIsUsedAsClient (line 76) | public function testFileSystemDriverIsS3WhenS3ClientIsUsedAsClient()
method testGetTempFilePath (line 88) | public function testGetTempFilePath()
method testPdfOptions (line 97) | public function testPdfOptions()
method testImageOptions (line 104) | public function testImageOptions()
method testContentType (line 116) | public function testContentType()
method testPagesIsEmpty (line 123) | public function testPagesIsEmpty()
method testPagesIsNotEmpty (line 128) | public function testPagesIsNotEmpty()
method testPushContents (line 135) | public function testPushContents()
method testPageBreak (line 144) | public function testPageBreak()
method testAddPages (line 158) | public function testAddPages()
method testToPdf (line 176) | public function testToPdf()
method testToPng (line 188) | public function testToPng()
method testToJpg (line 199) | public function testToJpg()
method testToGif (line 210) | public function testToGif()
FILE: tests/PrivateAndProtectedMethodsAccessibleTrait.php
type PrivateAndProtectedMethodsAccessibleTrait (line 4) | trait PrivateAndProtectedMethodsAccessibleTrait
method invokeMethod (line 15) | public function invokeMethod(&$object, $methodName, array $parameters ...
FILE: tests/RunnerTest.php
class RunnerTest (line 9) | class RunnerTest extends \PHPUnit_Framework_TestCase
method setUp (line 13) | public function setUp()
method testVerifyBinary (line 21) | public function testVerifyBinary()
Condensed preview — 18 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (54K chars).
[
{
"path": ".gitignore",
"chars": 42,
"preview": ".editorconfig\n.env.php\n/build\n/vendor\n/bin"
},
{
"path": "README.md",
"chars": 8482,
"preview": "# PhantomMagick\n\n### For PhantomMagick version 1, please use the [1.0.2 branch](https://github.com/anam-hossain/phantomm"
},
{
"path": "composer.json",
"chars": 1102,
"preview": "{\n \"name\": \"anam/phantommagick\",\n \"description\": \"PhantomMagick provides a simple API to ease the process of conve"
},
{
"path": "phpunit.xml.dist",
"chars": 926,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<phpunit \n colors=\"true\"\n convertErrorsToExceptions=\"true\"\n convertNotic"
},
{
"path": "src/Adapter.php",
"chars": 2762,
"preview": "<?php\nnamespace Anam\\PhantomMagick;\n\nuse Exception;\nuse InvalidArgumentException;\n\nclass Adapter\n{\n /**\n * The dr"
},
{
"path": "src/Converter.php",
"chars": 20609,
"preview": "<?php\nnamespace Anam\\PhantomMagick;\n\nuse Exception;\nuse RuntimeException;\nuse InvalidArgumentException;\nuse Anam\\Phantom"
},
{
"path": "src/ConverterServiceProvider.php",
"chars": 297,
"preview": "<?php\nnamespace Anam\\PhantomMagick;\n\nuse Illuminate\\Support\\ServiceProvider;\n\nclass ConverterServiceProvider extends Ser"
},
{
"path": "src/Exception/FileFormatNotSupportedException.php",
"chars": 129,
"preview": "<?php\n\nnamespace Anam\\Html2PdfConverter\\Exception;\n\nuse Exception;\n\nclass FileFormatNotSupportedException extends Except"
},
{
"path": "src/Exception/FileNotFoundException.php",
"chars": 119,
"preview": "<?php\n\nnamespace Anam\\Html2PdfConverter\\Exception;\n\nuse Exception;\n\nclass FileNotFoundException extends Exception\n{\n\n}\n"
},
{
"path": "src/Facades/Converter.php",
"chars": 194,
"preview": "<?php\nnamespace Anam\\PhantomMagick\\Facades;\n\nuse Illuminate\\Support\\Facades\\Facade;\n\nclass Converter extends Facade\n{\n "
},
{
"path": "src/Runner.php",
"chars": 4054,
"preview": "<?php\nnamespace Anam\\PhantomMagick;\n\nuse Exception;\nuse Anam\\PhantomMagick\\Str;\n\nclass Runner\n{\n /**\n * Executabl"
},
{
"path": "src/Str.php",
"chars": 629,
"preview": "<?php\nnamespace Anam\\PhantomMagick;\n\nclass Str\n{\n /**\n * This method is the part of illuminate/support package.\n "
},
{
"path": "src/scripts/phantom_magick.js",
"chars": 2884,
"preview": "var page = require('webpage').create(),\n system = require('system'),\n quality = system.args[5] || '70',\n orient"
},
{
"path": "tests/AdapterTest.php",
"chars": 487,
"preview": "<?php\nnamespace Anam\\PhantomMagick\\Test;\n\nuse Exception;\nuse RuntimeException;\nuse InvalidArgumentException;\nuse Anam\\Ph"
},
{
"path": "tests/ConverterTest.php",
"chars": 5970,
"preview": "<?php\nnamespace Anam\\PhantomMagick\\Test;\n\nuse Exception;\nuse RuntimeException;\nuse Mockery;\nuse Anam\\PhantomMagick\\Conve"
},
{
"path": "tests/PrivateAndProtectedMethodsAccessibleTrait.php",
"chars": 730,
"preview": "<?php\nnamespace Anam\\PhantomMagick\\Test;\n\ntrait PrivateAndProtectedMethodsAccessibleTrait\n{\n /**\n * Call protecte"
},
{
"path": "tests/RunnerTest.php",
"chars": 422,
"preview": "<?php\nnamespace Anam\\PhantomMagick\\Test;\n\nuse Exception;\nuse RuntimeException;\nuse InvalidArgumentException;\nuse Anam\\Ph"
},
{
"path": "tests/test_page.html",
"chars": 703,
"preview": "<html>\n\t<head>\n\t\t<title>PhantomMagick</title>\n\t</head>\n\t<body>\n\t\t<h1>Testing PhantomMagick</h1>\n\t\t<p>\n\t\t\tLorem Ipsum is "
}
]
About this extraction
This page contains the full source code of the anam-hossain/phantommagick GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 18 files (49.4 KB), approximately 12.9k tokens, and a symbol index with 105 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.