Hongmu Notes
Home Language Notes PHP converts web pages into PDF files.
Language Notes PHP

PHP converts web pages into PDF files.

PHP converts web pages into PDF files.

1. Install TechnicCom/TCPdf

2. Code:

<?php
// 引入TCPDF类文件
require_once './vendor/autoload.php';
require('../../action/class/common.php');
// use TCPDF\TCPDF;
$file = glob('../bak/*.png');

if(empty($file[0])){
    die('文件已经全部上传完成!');
}

$filename = basename($file[0]);
$puzi = explode('-',str_replace('.png','',$filename));

// print_r($file[0]);die;

$puziId = $puzi[0];
// 查询数据库,看是否存在同名文件
$sql = "SELECT * FROM `M_musicScore` WHERE `scoreID` = {$puziId} ORDER BY `num` DESC";
$result = mysqli_query($conn,$sql);
$data = mysqli_fetch_array($result, MYSQLI_ASSOC);
// print_r($data);die;

$s = new diaomao();
// $s->puziMake($s->jiamiPuZi(105349));
    
    
if(!empty($data['scoreID']) && $data['pdf'] !== 1){
    // 生成PDF文件名
    $pdfname = preg_replace('/[^\p{L}\p{N}\s]/u', ' ', $data['title']) . '-' . $data['scoreID'] . '.pdf';
    $pdfname = __DIR__ .'/pdf/'. $pdfname;
    // print_r($pdfname);
    // die;
    // print_r($pdfname);die;
    // 谱子存在,查询bak目录谱子是否齐全
    $files = glob('../bak/'.$data['scoreID'].'-*.png');
    // print_r($files);
    // print_r('../bak/'.$data['scoreID'].'-*.png');
    if(count($files) == $data['num']){
        foreach ($files as $k=>$v){
            $html.='<p style="text-align:center;"><img src="../bak/'.$data['scoreID'].'-'.$k.'.png"></p>';
        }
      $html = rtrim($html, "<br>");
    }
    // 创建TCPDF对象
    $pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
    
    // 设置文档属性和页面选项
    $pdf->SetCreator('HONGMU');
    $pdf->SetAuthor('作者');
    $pdf->SetTitle('标题');
    $pdf->SetSubject('WWW.I9J.CN');
    
    $pdf->SetHeaderData('', 0, '', '', array(0,0,0), array(255,255,255));
    
    // 设置页眉的logo和样式
    $pdf->setFooterData(array(0,0,0), array(255,255,255));
    
    // 添加新页面,并将HTML页面装入PDF文件
    $pdf->AddPage();
    $pdf->writeHTML($html, true, false, true, false, '');
    
    // 保存PDF文件
    $pdf->Output($pdfname , 'F');
    // 将数据表的pdf值设置为1
    $updateSql = "UPDATE `M_musicScore` SET `pdf` = 1 WHERE `scoreID` = {$puziId}";
    mysqli_query($conn, $updateSql);
    // 移动文件到pdf目录
    if (!file_exists(__DIR__ . '/pdf')) {
        // 如果pdf目录不存在,则创建pdf目录
        @mkdir(__DIR__ . '/yunpan');
    }
    foreach ($files as $k => $v) {
    $newFilePath = str_replace('bak', 'yunpan', $v);
    if (rename($v, $newFilePath)) {
    } else {
        die( '文件移动失败!<br>');
    }
    }
    
    if (mysqli_affected_rows($conn) > 0) {
        // 输出PDF文件
        // $pdf->Output('预览.pdf', 'I');
        echo '成功生成pdf文件';
    } else {
        die( '数据库写入失败!<br>');
    }
    
}else{
    // $files = glob('../bak/'.$data['scoreID'].'-*.png');
    // // print_r($files);die;
    // // print_r('../bak/'.$data['scoreID'].'-*.png');
    // if(!empty($files)){
    //     foreach ($files as $k=>$v){
    //         $newFilePath = str_replace('bak', 'yunpan', $v);
    //         if (rename($v, $newFilePath)) {
    //                 echo '以将文件移动到备份目录bak1。<br>';
    //             } else {
    //                 die( '文件移动失败!<br>');
    //             }
    //     }
    // }
    die('文件不齐全');
}

 

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 189
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

(PC+WAP) – Marketing-oriented website template for building energy efficiency shading solutions (pbootCMS); Download source code for energy-efficient building websites – 0724

(PC+WAP) – Marketing-oriented website template for building energy efficiency shading solutions (pbootCMS); Download source code for energy-efficient building websites – 0724 Practical Collection pbootcms Template

A marketing-oriented PbootCMS website template for building energy efficiency and shading products, compatible with both PC and mobile devices. The design features a fresh, eco-friendly aesthetic that emphasizes energy conservation and environmental sustainability. The page highlights shading products, energy-saving solutions, and project cases, enabling building energy efficiency companies to efficiently acquire online customers and showcase their technical advantages. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extract...
👁 40
Responsive online education and training website template 0190

Responsive online education and training website template 0190 Practical Collection Yiyou template

An eyouCMS responsive website template designed specifically for online education and training enterprises. Its modern educational design effectively showcases online courses, faculty resources, teaching platforms, and student achievements. This template helps edtech companies attract students online and enhance their brand awareness. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eyouCMS | eyou...
👁 54
Empire CMS personal blog articles news information responsive HTML5 responsive mobile template 053

Empire CMS personal blog articles news information responsive HTML5 responsive mobile template 053 Practical Collection empire template

The template uses the new version of Empire CMS as its core. The whole site design is high-end and simple, and the SEO is reasonable! Suitable for personal blogs, information, articles, adaptive mobile phones and other tablet devices! All modifications are managed in the background! Easy and fast! The whole site list adopts the drop-down loading method. For SEO reliability, the automatic drop-down loading method and the real paging source code are used! Preview image decompression password 🔒 Hidden content: View after commenting If there is no password prompt on the download page, the password defaults to...
👁 1646
Responsive Vocational Education Website Template 0851

Responsive Vocational Education Website Template 0851 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the vocational education sector, featuring a professional design style that effectively showcases vocational education courses, training programs, employment services, and faculty resources. It helps vocational training institutions attract learners online and enhance their brand awareness. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 45
(PC + WAP) Green Marketing Generator – pbootCMS Website Template; Download Source Code for Mechanical and Electrical Equipment Websites – 0092

(PC + WAP) Green Marketing Generator – pbootCMS Website Template; Download Source Code for Mechanical and Electrical Equipment Websites – 0092 Practical Collection pbootcms Template

This PbootCMS template features a green marketing design approach, specifically tailored for the generator and electromechanical equipment industry, and is compatible with both PC and mobile devices. Its professional, robust design effectively showcases generator sets and industrial application cases, enabling generator manufacturers or electromechanical companies to efficiently present their products online and attract targeted customer inquiries. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin
👁 33
(Adaptive Mobile Version) Water Sports Equipment PBootCMS Website Template – Download Source Code for a Diving Service Company Website – 0725

(Adaptive Mobile Version) Water Sports Equipment PBootCMS Website Template – Download Source Code for a Diving Service Company Website – 0725 Practical Collection pbootcms Template

A PbootCMS website template for water sports equipment and diving services, compatible with both PC and WAP devices. Its clean and dynamic design is ideal for showcasing diving gear, water sports equipment, and training services. This template helps outdoor sports companies attract extreme sports enthusiasts online. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn | Related Articles...
👁 52