search
HomeBackend DevelopmentPHP ProblemHow to convert work to pdf in php

How to convert work to pdf in php

Sep 30, 2021 pm 12:11 PM
pdfphp

方法:1、打开php.ini文件,添加“extension=php_com_dotnet.dll”代码,去掉“com.allow_dcom=true”前的“;”;2、配置office支持;3、利用PDFConverter类中的方法进行转换。

How to convert work to pdf in php

本教程操作环境:windows7系统、PHP7.1版,DELL G3电脑

一、配置PHP扩展

如果是 PHP5.4 以前的版本,需要在 php.ini 里把 com.allow_dcom = true 打开(即去掉前面的分号)。

如果是 PHP5.4 之后的版本,则要在 php.ini 里增加一行扩展 extension = php_com_dotnet.dll

重启 Apache 或 IIS 服务器,打印 phpinfo() 信息,检查 com_dotnet 扩展是开启。

↑ 检查 php 的 ext 目录中 是否存在 com_dotnet.dll 文件,如果没有请自行下载对应版本的 dll

二、配置office支持

OpenOffice 是一套开源跨平台的办公软件,由许多自由软件人士共同来维持,让大家能在 Microsoft Office 之外,还能有免费的 Office 可以使用。

OpenOffice 与微软的办公软件套件兼容,能将 doc、xls、ppt 等文件转换为 PDF 格式,其功能绝对不比 Microsoft Office 差。

OpenOffice 官网:http://www.openoffice.org/

OpenOffice 下载:http://www.openoffice.org/download/index.html

OpenOffice 需要 java 支持,请确认安装了 JDK,并配置了 JRE 环境变量。

1. 配置组件服务

OpenOffice 安装完成之后,按 win+R 快捷键进入运行菜单,输入 Dcomcnfg 打开组件服务。

 [组件服务] >> [计算机] >> [我的电脑] >> [DCOM配置] >> [OpenOffice Service Manager]

右键打开属性面板,选择安全选项卡,分别在 启动和激活权限访问权限 上勾选自定义,添加 Everyone 的权限。

↑ 启动和激活权限 和 访问权限 都使用自定义配置

↑ 添加 Everyone 用户组,记得确认前先检查名称

↑ 两个自定义配置相同,允许 Everyone 拥有所有权限

再选择标识选项卡,勾选 交互式用户,保存设置后退出。

2. 后台运行软件

安装完 OpenOffice 后,需要启动一次确认软件可以正常运行,然后再打开命令行运行以下命令:

切换到安装目录:  cd C:\Program Files\OpenOffice 4\program  

后台运行该软件:  soffice -headless-accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard  

PS:该命令只需要执行一次,就可以使软件一直在后台运行,即使重启服务器也不受影响。

三、实现文件转换

PDF 转换工具(支持 doc, docx, xls, xlsx, ppt, pptx 等格式)

class PDFConverter
{    private $com;    /**
     * need to install openoffice and run in the background
     * soffice -headless-accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard     */
    public function __construct()
    {        try {            $this->com = new COM('com.sun.star.ServiceManager');
        } catch (Exception $e) {            die('Please be sure that OpenOffice.org is installed.');
        }
    }    /**
     * Execute PDF file(absolute path) conversion
     * @param $source [source file]
     * @param $export [export file]     */
    public function execute($source, $export)
    {        $source = 'file:///' . str_replace('\\', '/', $source);        $export = 'file:///' . str_replace('\\', '/', $export);        $this->convertProcess($source, $export);
    }    /**
     * Get the PDF pages
     * @param $pdf_path [absolute path]
     * @return int     */
    public function getPages($pdf_path)
    {        if (!file_exists($pdf_path)) return 0;        if (!is_readable($pdf_path)) return 0;        if ($fp = fopen($pdf_path, &#39;r&#39;)) {            $page = 0;            while (!feof($fp)) {                $line = fgets($fp, 255);                if (preg_match(&#39;/\/Count [0-9]+/&#39;, $line, $matches)) {                    preg_match(&#39;/[0-9]+/&#39;, $matches[0], $matches2);                    $page = ($page < $matches2[0]) ? $matches2[0] : $page;
                }
            }            fclose($fp);            return $page;
        }        return 0;
    }    private function setProperty($name, $value)
    {        $struct = $this->com->Bridge_GetStruct(&#39;com.sun.star.beans.PropertyValue&#39;);        $struct->Name = $name;        $struct->Value = $value;        return $struct;
    }    private function convertProcess($source, $export)
    {        $desktop_args = array($this->setProperty(&#39;Hidden&#39;, true));        $desktop = $this->com->createInstance(&#39;com.sun.star.frame.Desktop&#39;);        $export_args = array($this->setProperty(&#39;FilterName&#39;, &#39;writer_pdf_Export&#39;));        $program = $desktop->loadComponentFromURL($source, &#39;_blank&#39;, 0, $desktop_args);        $program->storeToURL($export, $export_args);        $program->close(true);
    }
}

使用 PDFConverter(必须传入绝对路径)

$arr = array(&#39;doc&#39;, &#39;docx&#39;, &#39;xls&#39;, &#39;xlsx&#39;, &#39;ppt&#39;, &#39;pptx&#39;);

$converter = new PDFConverter();

foreach ($arr as $ext) {
    $source = __DIR__ . &#39;/office/test.&#39; . $ext;
    $export = __DIR__ . &#39;/pdf/test.&#39; . $ext . &#39;.pdf&#39;;
    $converter->execute($source, $export);
    echo &#39;<p>&#39; . $ext . &#39; Done</p>&#39;;
}

推荐学习:《PHP视频教程

The above is the detailed content of How to convert work to pdf in php. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools