greetingCardPrintUtil.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace common\components;
  3. use bizHd\order\services\OrderService;
  4. use Yii;
  5. /**
  6. * 订单节日贺卡云打印(文字暂写死,纸张规格可配置)
  7. */
  8. class greetingCardPrintUtil
  9. {
  10. /**
  11. * 根据订单 ID 打印节日贺卡
  12. */
  13. public static function printByOrderId($orderId, $mainId = 0, array $printOptions = [])
  14. {
  15. $order = OrderService::getById($orderId);
  16. if (empty($order)) {
  17. throw new CloudPrinterApiException('订单不存在');
  18. }
  19. if ($mainId > 0) {
  20. OrderService::valid($order, $mainId);
  21. }
  22. return self::printByData(self::buildDefaultData(), $printOptions);
  23. }
  24. /**
  25. * 直接打印贺卡
  26. */
  27. public static function printByData(array $data = [], array $printOptions = [])
  28. {
  29. if (!cloudPrintUtil::isEnabled()) {
  30. throw new CloudPrinterApiException('链科云打印未启用,请先在 .env 配置 LIANKENET_*');
  31. }
  32. $paper = cloudPrintPaperSpec::resolve(array_merge([
  33. 'scene' => cloudPrintPaperSpec::SCENE_GREETING_CARD,
  34. ], $printOptions));
  35. $data['paper'] = $paper;
  36. $html = self::renderHtml($data);
  37. return (new cloudPrintUtil())->printHtml($html, $paper['dmPaperSize']);
  38. }
  39. /**
  40. * 默认贺卡文案(写死,后续可改为订单 cardInfo / 收花人姓名等)
  41. */
  42. public static function buildDefaultData()
  43. {
  44. return [
  45. 'cardTitle' => '生日快乐贺卡',
  46. 'toText' => 'To 陈小姐',
  47. 'titleText' => '生日快乐',
  48. 'messageLines' => [
  49. '愿你今天被鲜花和温柔包围,',
  50. '生日快乐,天天开心。',
  51. ],
  52. 'fromText' => 'From 你的朋友',
  53. ];
  54. }
  55. /**
  56. * 渲染贺卡 HTML
  57. */
  58. public static function renderHtml(array $data)
  59. {
  60. $data = array_merge(self::buildDefaultData(), $data);
  61. if (empty($data['paper'])) {
  62. $data['paper'] = cloudPrintPaperSpec::resolve([
  63. 'scene' => cloudPrintPaperSpec::SCENE_GREETING_CARD,
  64. ]);
  65. }
  66. $template = Yii::getAlias('@common/templates/greeting-card-a4.php');
  67. if (!is_file($template)) {
  68. throw new CloudPrinterApiException('节日贺卡模板不存在');
  69. }
  70. ob_start();
  71. include $template;
  72. return (string)ob_get_clean();
  73. }
  74. }