yjbdcController.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. import moment from 'moment';
  2. import fs from 'fs';
  3. import commonModel from '../../model/commonModel.js';
  4. import config from '../../config/index.js';
  5. import _ from 'lodash';
  6. import axios from 'axios';
  7. import { Encrypt, Decrypt } from '../../util/crypto/index.js';
  8. import { stringUtils } from '../../util/stringClass.js';
  9. import WXBizDataCrypt from '../../util/WXBizDataCrypt.js';
  10. import { globalCache } from '../../util/GlobalCache.js';
  11. import constantClass from '../../util/constant/index.js';
  12. import yjbdc from '../../model/yjbdc.js';
  13. import aiController from './aiController.js';
  14. import PDFDocument from 'pdfkit';
  15. import tencentcloud from 'tencentcloud-sdk-nodejs-ocr';
  16. const ONE_DAY_MAX_BUILD_COUNT=12;//一天最大生成数
  17. const OcrClient = tencentcloud.ocr.v20181119.Client;
  18. //小程序登录
  19. export async function YJBDCLogin(ctx) {
  20. let param = ctx.request.body;
  21. if (param.param) {
  22. const paramStr = Decrypt(param.param, config.urlSecrets.aes_key, config.urlSecrets.aes_iv);
  23. //console.log("paramStr:"+paramStr);
  24. param = JSON.parse(paramStr);
  25. }
  26. const code = param.Code;
  27. //console.log("code:"+code);
  28. const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${config.wx.yjbdc_appid}&secret=${config.wx.yjbdc_appsecret}&js_code=${code}&grant_type=authorization_code`;
  29. let result = await axios.get(url)
  30. .then(res => {
  31. const json = res.data;
  32. //console.log("json:"+json);
  33. if (json && json.openid) {
  34. param.OpenID = json.openid;
  35. param.sessionKey = json.session_key;
  36. if (json.unionid)
  37. param.UnionID = json.unionid;
  38. return {errcode: 10000};
  39. }
  40. else {
  41. return json;
  42. }
  43. })
  44. .catch(err => {
  45. return {errcode: 101, errStr: err};
  46. });
  47. if (result.errcode == 10000) {
  48. delete param.Code;
  49. if (param.sessionKey && param.iv && param.encryptedData){
  50. //console.log("param.sessionKey:"+param.sessionKey);
  51. const pc = new WXBizDataCrypt(config.wx.yjbdc_appid, param.sessionKey);
  52. const dataUnionID = pc.decryptData(param.encryptedData , param.iv);
  53. //console.log(dataUnionID);
  54. param.UnionID = dataUnionID.unionId;
  55. }
  56. delete param.sessionKey;
  57. delete param.iv;
  58. delete param.encryptedData;
  59. //todo
  60. //param.OpenID="o4UHq4gaNlHfdTWxgl3fTgC1mFsI";
  61. let userList = await yjbdc.GetUsersInfo(param);
  62. if (userList.length > 0) {
  63. param.LastLoginTime = new Date();
  64. const time1 = moment(userList[0].ProductServiceTime).format('YYYY-MM-DD HH:mm:ss');
  65. const time3 = moment().format('YYYY-MM-DD HH:mm:ss');
  66. if (time1 < time3)
  67. param.IsMember = 0;
  68. delete param.Introducer;
  69. delete param.UserSource;
  70. delete param.SourceID;
  71. //console.log(param.NickName);
  72. if (param.NickName == "陌生用户") {
  73. delete param.NickName;
  74. delete param.AvatarUrl;
  75. delete param.Language;
  76. delete param.Gender;
  77. delete param.City;
  78. delete param.Province;
  79. delete param.Country;
  80. }
  81. await yjbdc.UpdateUsers(param);
  82. userList = await yjbdc.GetUsersInfo(param);
  83. }
  84. else {
  85. param.NickName = "陌生用户";
  86. param.AvatarUrl = "../images/userface_default.png";
  87. param.CreateTime = new Date();
  88. param.LastLoginTime = param.CreateTime;
  89. param.ProductServiceTime = param.CreateTime;
  90. const inseredID = await yjbdc.AddUsers(param);
  91. userList = await yjbdc.GetUsersInfo(param);
  92. }
  93. delete userList[0].OpenID;
  94. delete userList[0].UnionID;
  95. //产品支付是否显示
  96. if (param.ProgramVersion) {
  97. let param2 = {
  98. ProgramID: 186,
  99. Version: param.ProgramVersion,
  100. };
  101. let result3 = await commonModel.GetProductVersionList(param2);
  102. if (result3) {
  103. if ((param2.Version == result3[0].Version && result3[0].IsShowPay <= 0)
  104. || param2.Version > result3[0].Version) {
  105. userList[0].IsShow = result3[0].IsShowPay;
  106. }
  107. else {
  108. userList[0].IsShow = 1;
  109. }
  110. //针对iphone测试用户,永远是无支付状态
  111. if (userList[0].Brand == 'iPhone' && userList[0].WXLanguage == 'en-US'
  112. && userList[0].UserSource == '1001' && userList[0].IsPay == 0) {
  113. userList[0].IsShow = 0;
  114. }
  115. //针对微信测试用户,永远是无支付状态
  116. if ((userList[0].UserSource=='1001' && userList[0].System=="iOS 10.0.1")
  117. || (!userList[0].UserSource && (!userList[0].LastUserSource || userList[0].LastUserSource>10000))
  118. || userList[0].NickName.indexOf("dgztest")>=0){
  119. userList[0].IsShow=-1;
  120. }
  121. if (userList[0].IsMember===1)
  122. userList[0].IsShow=1;
  123. }
  124. }
  125. result = {errcode: 10000, result: userList[0]};
  126. }
  127. ctx.body = result;
  128. }
  129. //OCR获取单词
  130. export async function OCRImageData(ctx) {
  131. const params = ctx.request.body;
  132. const clientConfig = {
  133. credential: {
  134. secretId: config.tencentcloud.secretId,
  135. secretKey: config.tencentcloud.secretKey,
  136. },
  137. region: "ap-guangzhou",
  138. profile: {
  139. httpProfile: {
  140. endpoint: "ocr.tencentcloudapi.com",
  141. },
  142. },
  143. };
  144. // 实例化要请求产品的client对象,clientProfile是可选的
  145. const client = new OcrClient(clientConfig);
  146. const result = await client.GeneralBasicOCR(params);
  147. let param2={};
  148. param2.UserID=ctx.query.UserID;
  149. param2.CreateTime=moment().format('YYYY-MM-DD HH:mm:ss');
  150. param2.Params=JSON.stringify(params);
  151. param2.JSONString=JSON.stringify(result);
  152. await yjbdc.AddOCRInfo(param2);
  153. ctx.body = {"errcode": 10000, result};
  154. }
  155. //AI生成文章
  156. export async function GenerateArticle(ctx) {
  157. const url='GenerateArticle?UserID='+ctx.query.UserID;
  158. let result = globalCache.get(url);
  159. if (result === 0) {
  160. const params = ctx.request.body;
  161. const words = params.Words;
  162. let articleStyle = params.ArticleStyle;
  163. if (words){
  164. const menuConfig=constantClass.GetYJBDCGenerateConfig();
  165. let content = "将"+words+"这些单词生成一篇英文文章。要求"+
  166. "[难度];"+
  167. "文章类型是'"+articleStyle+"([类型])';"+
  168. "要求提供丰富上下文线索、清晰的文章结构;"+
  169. "文章单词数在200个左右,最多不能超过300个;"+
  170. "文章按每句分成数组,且每句都有中文翻译[补充1];"+
  171. "提供5道针对文章阅读理解的单项选择题,各有四个唯一选项,并提供答案;"+
  172. "单项选择题和选项也要有中文翻译;"+
  173. "必须确保用户提供的每个单词(除像'fuck'、'shit'等脏话外)至少在文章中出现一次,可以是原形或某种变形(第三人称单数、复数、过去式、过去分词、现在分词、比较级、最高级等等所有可能的变形形式)。比如用户输入'go',文章除了'go'以外,也可以生成像'goes'、'went'、'gone'、'going'等单词;"+
  174. "内容格式为JSON,必须严格按照以下格式,不能有任何字段名错误或缺失:{"+
  175. " \"ArticleEnglish\":[\"<英文文章句子1>\",\"<英文文章句子2>\"...],"+
  176. " \"ArticleChinese\":[\"<中文翻译句子1>\",\"<中文翻译句子2>\"...],"+
  177. " \"Question\":[{"+
  178. " \"QuestionEnglish\":\"<英语题目1>\","+
  179. " \"QuestionChinese\":\"<题目1中文翻译>\","+
  180. " \"OptionsEnglish\":[\"A.<英语选项1>\",\"B.<英语选项2>\",\"C.<英语选项3>\",\"D.<英语选项4>\"],"+
  181. " \"OptionsChinese\":[\"A.<选项1中文翻译>\",\"B.<选项2中文翻译>\",\"C.<选项3中文翻译>\",\"D.<选项4中文翻译>\"],"+
  182. " \"Answer\":\"<答案>\""+
  183. " }...]"+
  184. "}";
  185. if (!params.Level || params.Level=="" || params.Level==undefined || params.Level>="4"){
  186. params.Level="0";
  187. }
  188. content = content.replace("[难度]",menuConfig.Level[Number(params.Level)].Content);
  189. // if (articleStyle=="随机" || articleStyle=="任意") {
  190. // // 获取ARTICLE_STYLE对象的所有键(文章类型)
  191. // const articleTypes = Object.keys(ARTICLE_STYLE);
  192. // // 随机选择一个文章类型
  193. // const randomIndex = stringUtils.Random(0, articleTypes.length-1);
  194. // articleStyle = articleTypes[randomIndex];
  195. // }
  196. for(let i=0;i<menuConfig.ArticleStyle.length;i++){
  197. if (menuConfig.ArticleStyle[i].Name==articleStyle){
  198. content = content.replace("[类型]",menuConfig.ArticleStyle[i].Content);
  199. break;
  200. }
  201. }
  202. //console.log("content:"+content);
  203. // 从请求参数中获取AI提供者,如果没有指定则使用默认值
  204. let aiProvider = '';
  205. for(let i=0;i<menuConfig.AIVersion.length;i++){
  206. if (menuConfig.AIVersion[i].Version==params.AIVersion){
  207. aiProvider=menuConfig.AIVersion[i].Model;
  208. break;
  209. }
  210. }
  211. //给用户一些比较好的体验
  212. if (params.AIVersion=="1.0"){
  213. aiProvider = 'ali-Moonshot-Kimi-K2-Instruct';
  214. }
  215. else if (params.AIVersion=="1.5"){
  216. aiProvider = 'doubao-kimi-k2-250711';
  217. }
  218. if (aiProvider.indexOf("llama")>=0)
  219. content=content.replace("[补充1]",",如果生成的JSON中有ArticleEnglishCorrected和ArticleChineseCorrected,直接覆盖原有的ArticleEnglish和ArticleChinese,不要再生成。");
  220. else
  221. content=content.replace("[补充1]","");
  222. try {
  223. //开始时间
  224. let timeStart=new Date().getTime();
  225. // 使用aiController生成文章
  226. let result2 = await aiController.generateArticle(content, aiProvider);
  227. //console.log(result2);
  228. //debugger;
  229. // 校验和修复JSON结构
  230. result2 = aiController.validateAndFixJSON(result2);
  231. //console.log("JSON结构已校验和修复");
  232. result2 =aiController.normalizeArticleFields(result2);
  233. // 解析JSON以增强FormsOfWords
  234. const jsonObj = JSON.parse(result2);
  235. // 增强FormsOfWords,检测文章中单词的变形形式和拼写错误
  236. const enhancedJsonObj = aiController.enhanceFormsOfWords(jsonObj, words);
  237. // 将增强后的对象转回JSON字符串
  238. result2 = JSON.stringify(enhancedJsonObj);
  239. //console.log("FormsOfWords已增强,添加了单词变形和拼写错误检测");
  240. // 记录增强后的单词数量
  241. if (enhancedJsonObj.FormsOfWords && Array.isArray(enhancedJsonObj.FormsOfWords)) {
  242. console.log(`增强了${enhancedJsonObj.FormsOfWords.length}个单词的变形形式`);
  243. }
  244. let timeEnd=new Date().getTime();
  245. let param2={};
  246. param2.UserID=ctx.query.UserID;
  247. param2.CreateTime=moment().format('YYYY-MM-DD HH:mm:ss');
  248. param2.Words=words;
  249. param2.Level=params.Level;
  250. param2.articleStyle=articleStyle;
  251. param2.AIProvider=aiProvider;
  252. param2.BuildStr=content;
  253. param2.GenerateTime=Math.round((timeEnd-timeStart)/1000);
  254. console.log("生成时间:"+param2.GenerateTime+"秒");
  255. // 尝试解析JSON以获取ArticleStart
  256. const jsonObj2 = JSON.parse(result2);
  257. param2.ArticleStart = jsonObj2.ArticleEnglish && jsonObj2.ArticleEnglish.length > 0 ? jsonObj2.ArticleEnglish[0] : "No content available";
  258. // 去除JSON字符串中的所有换行符(\r\n, \n, \r)
  259. param2.JSONString=JSON.stringify(result2.replace(/[\r\n]+/g, ''));
  260. param2.Flag=0;
  261. let idInsert= await yjbdc.AddArticleInfo(param2);
  262. //result = { errcode: 10000, result: result2 };
  263. let result3={};
  264. result3.ID=idInsert.insertId;
  265. result3.Content=result2;
  266. result3.IsNew=true;
  267. result = { errcode: 10000, result: result3 };
  268. globalCache.set(url, result, config.BufferMemoryTime);
  269. console.log("缓存60秒");
  270. }
  271. catch(err){
  272. console.error("AI生成错误:"+err);
  273. result = { errcode: 10000, result: "-1" };
  274. }
  275. }
  276. else{
  277. console.log("空单词串");
  278. result = { errcode: 10000, result: "-1" };
  279. }
  280. }
  281. ctx.body = result;
  282. }
  283. export async function GetYJBDCGenerateConfig(ctx) {
  284. const param = {
  285. UserID: ctx.query.UserID || 0,
  286. };
  287. let result=constantClass.GetYJBDCGenerateConfig();
  288. for (let i=0;i<result.Level.length;i++){
  289. delete result.Level[i].English;
  290. }
  291. for(let i=0;i<result.ArticleStyle.length;i++){
  292. delete result.ArticleStyle[i].English;
  293. delete result.ArticleStyle[i].Content;
  294. }
  295. if (param.UserID>3){
  296. result.AIVersion.splice(2,result.AIVersion.length-2);
  297. // if (param.UserID==185){
  298. // const configArr=constantClass.GetYJBDCGenerateConfig();
  299. // result.AIVersion.push(configArr.AIVersion[5]);
  300. // }
  301. // if (param.UserID<4){
  302. // const configArr=constantClass.GetYJBDCGenerateConfig();
  303. // result.AIVersion.push(configArr.AIVersion[6]);
  304. // }
  305. }
  306. ctx.body = {"errcode": 10000, result:result};
  307. }
  308. //获得文章列表或具体文章
  309. export async function GetYJBDCArticleList(ctx) {
  310. const param = {
  311. UserID: ctx.query.UserID || 0,
  312. ID:ctx.query.ID || 0,
  313. IsChoiceness:ctx.query.IsChoiceness || 0,//是否是精选文章
  314. IsTodayCount: ctx.query.IsTodayCount || false,
  315. IsNew: ctx.query.IsNew || 0,
  316. };
  317. // 尝试从缓存获取
  318. const url='GetYJBDCArticleList?IsChoiceness='+param.IsChoiceness+'&UserID='+param.UserID+'&ID='+param.ID;
  319. let result = globalCache.get(url);
  320. if (param.IsNew==1)
  321. result=0;
  322. if (result === 0) {
  323. result = await yjbdc.GetYJBDCArticleList(param);
  324. if (param.ID==0){
  325. let menuConfig=constantClass.GetYJBDCGenerateConfig();
  326. for(let i=0;i<result.length;i++){
  327. let item=result[i];
  328. item.CreateTime=moment(item.CreateTime).format("YYYY年MM月DD日 HH:mm");
  329. //debugger;
  330. item.LevelStr=menuConfig.Level[item.Level].Name;
  331. }
  332. }
  333. globalCache.set(url, result, config.BufferMemoryTime);
  334. console.log("缓存"+config.BufferMemoryTime+"秒");
  335. }
  336. //console.log(result.length);
  337. if (param.IsTodayCount && !param.ID){
  338. let count=0,unReadCount=0;
  339. const today=moment().format("YYYY年MM月DD日 00:00");
  340. for(let i=0;i<result.length;i++){
  341. if (result[i].CreateTime>=today)
  342. count++;
  343. if (result[i].Flag==0 && result[i].ReadCount==0)
  344. unReadCount++;
  345. }
  346. let maxcount=ONE_DAY_MAX_BUILD_COUNT;
  347. if (param.UserID<4){
  348. maxcount=100;
  349. }
  350. result={
  351. TodayCount:count,
  352. MaxCount:maxcount,
  353. UnReadCount:unReadCount,
  354. };
  355. }
  356. else if (!param.ID){
  357. let arr=[];
  358. for(let i=0;i<result.length;i++){
  359. if (result[i].Flag==0)
  360. arr.push(result[i]);
  361. }
  362. result=arr;
  363. }
  364. // console.log(result.length);
  365. // console.log(result.TodayCount);
  366. ctx.body = {"errcode": 10000, result:result};
  367. }
  368. //删除生成的文章
  369. export async function DeleteYJBDCArticleList(ctx) {
  370. const param = {
  371. UserID: ctx.query.UserID || 0,
  372. ID: ctx.query.ID || 0,
  373. Flag:-1,
  374. };
  375. if (param.ID>0){
  376. const url='GetYJBDCArticleList?UserID='+param.UserID+"&ID=0";
  377. globalCache.delete(url);
  378. await yjbdc.UpdateYJBDCArticle(param);
  379. }
  380. ctx.body = {"errcode": 10000};
  381. }
  382. //更新阅读数
  383. export async function UpdateYJBDCArticleReadCount(ctx) {
  384. const param = {
  385. UserID: ctx.query.UserID || 0,
  386. ID: ctx.query.ID || 0,
  387. ReadCount:1,
  388. };
  389. if (param.ID>0){
  390. await yjbdc.UpdateYJBDCArticle(param);
  391. }
  392. ctx.body = {"errcode": 10000};
  393. }
  394. //生成PDF
  395. export async function GeneratePDF(ctx) {
  396. const params = ctx.request.body;
  397. if (!params || !params.Content) {
  398. ctx.status = 400;
  399. ctx.body = { error: 'Invalid request body: Content is required' };
  400. return;
  401. }
  402. const content = params.Content;
  403. const menuConfig=constantClass.GetYJBDCGenerateConfig();
  404. try {
  405. // 创建新的 PDF 文档 - 使用A4尺寸
  406. const doc = new PDFDocument({
  407. size: 'A4', // 使用标准A4尺寸 (595.28 x 841.89 points)
  408. margins: {
  409. top: 0,
  410. bottom: 0,
  411. left: 0,
  412. right: 0
  413. },
  414. autoFirstPage: true
  415. });
  416. // 注册中文字体
  417. doc.registerFont('ChineseFont', './public/fonts/方正黑体简体.TTF');
  418. // 定义字体选择函数
  419. const selectFont = (text, defaultFont = 'Helvetica') => {
  420. if (/[\u4E00-\u9FFF]/.test(text)) {
  421. return 'ChineseFont';
  422. }
  423. return defaultFont;
  424. };
  425. // 收集生成的 PDF 数据
  426. const chunks = [];
  427. doc.on('data', (chunk) => chunks.push(chunk));
  428. // 像素到点(pt)的转换函数
  429. const pixelToPt = (pixel) => pixel * (595.28 / 2100);
  430. // 获取文章内容
  431. let articleText = "";
  432. if (content.ArticleEnglish) {
  433. articleText = Array.isArray(content.ArticleEnglish) ?
  434. content.ArticleEnglish.join(" ") : content.ArticleEnglish;
  435. } else {
  436. articleText = "No content available";
  437. }
  438. articleText = articleText.replace(/<[^>]*>/g, '');
  439. // 获取单词列表
  440. let words = [];
  441. if (content.Words) {
  442. words = typeof content.Words === 'string' ?
  443. content.Words.split(",") :
  444. (Array.isArray(content.Words) ? content.Words : []);
  445. }
  446. // 获取问题列表
  447. let questions = [];
  448. if (content.Question && Array.isArray(content.Question)) {
  449. questions = content.Question;
  450. }
  451. let articleStyleArr=menuConfig.ArticleStyle;
  452. let articleStyle="Story";
  453. for(let i=0;i<articleStyleArr.length;i++){
  454. if (articleStyleArr[i].Name==content.ArticleStyle){
  455. articleStyle=articleStyleArr[i].English;
  456. break;
  457. }
  458. }
  459. // 1. 标题 - 文章类型
  460. doc.font(selectFont(articleStyle))
  461. .fontSize(pixelToPt(48))
  462. .text(articleStyle,
  463. pixelToPt(120), pixelToPt(110));
  464. // 2. 副标题 - 难度级别
  465. doc.font('Helvetica')
  466. .fontSize(pixelToPt(30))
  467. .text(menuConfig.Level[Number(content.Level)].English || "",
  468. pixelToPt(120), pixelToPt(170));
  469. // 3. 时间
  470. const currentDate = moment().format("YYYY年MM月DD日 HH:mm");
  471. if (params.CreateTime)
  472. currentDate=moment(params.CreateTime).format("YYYY年MM月DD日 HH:mm");
  473. doc.font('ChineseFont')
  474. .fontSize(pixelToPt(30))
  475. .text(currentDate,
  476. pixelToPt(120), pixelToPt(212));
  477. // 4. 黑线
  478. doc.rect(pixelToPt(120), pixelToPt(289), pixelToPt(537), pixelToPt(10))
  479. .fill('black');
  480. // 5. 单词列表
  481. doc.font('Helvetica')
  482. .fontSize(pixelToPt(36));
  483. let wordY = pixelToPt(364);
  484. words.slice(0, 10).forEach(word => {
  485. doc.text(word, pixelToPt(122), wordY, {
  486. width: pixelToPt(535),
  487. align: 'left'
  488. });
  489. wordY += pixelToPt(70);
  490. });
  491. // 6. 文章内容
  492. // 先计算文章内容的行数
  493. doc.font('Helvetica');
  494. // 使用48字号计算文本高度
  495. const fontSize48 = pixelToPt(48);
  496. doc.fontSize(fontSize48);
  497. const textHeight48 = doc.heightOfString(articleText, {
  498. width: pixelToPt(1240),
  499. lineGap: pixelToPt(40.5)
  500. });
  501. // 计算行数 (文本高度 / (字体大小 + 行间距))
  502. const lineHeight = fontSize48 + pixelToPt(40.5);
  503. const lineCount = Math.ceil(textHeight48 / lineHeight);
  504. // 如果行数超过18行,则使用42字号
  505. const fontSize = lineCount > 18 ? pixelToPt(42) : pixelToPt(48);
  506. // 渲染文章内容
  507. doc.fontSize(fontSize)
  508. .text(articleText, pixelToPt(740), pixelToPt(105), {
  509. width: pixelToPt(1240),
  510. lineGap: pixelToPt(40.5)
  511. });
  512. // 7. 黑线
  513. const articleEndY = doc.y;
  514. doc.rect(pixelToPt(120), articleEndY + pixelToPt(41),
  515. pixelToPt(1860), pixelToPt(10))
  516. .fill('black');
  517. // 8-13. 问题和答案
  518. if (questions.length > 0) {
  519. // 定义问题的X坐标位置
  520. const questionXPositions = [
  521. pixelToPt(120), // 问题1
  522. pixelToPt(120), // 问题2
  523. pixelToPt(740), // 问题3
  524. pixelToPt(740), // 问题4
  525. pixelToPt(1360) // 问题5
  526. ];
  527. // 存储每列最后一个选项的Y坐标位置
  528. let lastOptionYPositions = {
  529. column1: 0, // 用于跟踪第一列(问题1)的最后位置
  530. column2: 0, // 用于跟踪第二列(问题3)的最后位置
  531. };
  532. // 首先渲染问题1、3、5(第一行问题)
  533. const firstRowQuestions = [0, 2, 4]; // 问题1、3、5的索引
  534. for (const i of firstRowQuestions) {
  535. if (i < questions.length && questions[i]) {
  536. const currentX = questionXPositions[i];
  537. const currentY = articleEndY + pixelToPt(130); // 所有第一行问题的起始Y坐标相同
  538. // 渲染问题文本
  539. doc.font('Helvetica-Bold')
  540. .fontSize(pixelToPt(36))
  541. .text(`${i+1}. ${questions[i].QuestionEnglish || `Question ${i+1}`}`,
  542. currentX, currentY, {
  543. width: pixelToPt(540),
  544. align: 'left'
  545. });
  546. // 获取问题文本渲染后的Y坐标位置
  547. const questionEndY = doc.y;
  548. // 选项起始位置 = 问题结束位置 + 20像素间距
  549. let optionY = questionEndY + pixelToPt(28);
  550. // 渲染选项
  551. const options = questions[i].OptionsEnglish || [];
  552. const optionLabels = ['A', 'B', 'C', 'D'];
  553. // 设置选项标签宽度和选项总宽度
  554. const labelWidth = pixelToPt(40); // 标签(A./B./C./D.)的宽度
  555. const totalWidth = pixelToPt(496); // 选项的总宽度
  556. const contentWidth = totalWidth - labelWidth; // 选项内容的宽度
  557. options.forEach((opt, index) => {
  558. if (index < optionLabels.length) {
  559. // 提取选项内容,移除可能存在的标签前缀
  560. let optionContent = opt.replace(/^[A-D]\.\s*/, '');
  561. // 渲染选项标签(A./B./C./D.)
  562. doc.font('Helvetica')
  563. .fontSize(pixelToPt(36))
  564. .text(`${optionLabels[index]}.`, currentX, optionY, {
  565. width: labelWidth,
  566. align: 'left'
  567. });
  568. // 渲染选项内容,确保折行时与内容第一行对齐
  569. doc.font('Helvetica')
  570. .fontSize(pixelToPt(36))
  571. .text(optionContent, currentX + labelWidth, optionY, {
  572. width: contentWidth,
  573. align: 'left'
  574. });
  575. // 更新选项Y坐标,为下一个选项做准备
  576. // 获取当前位置,确保下一个选项在当前选项完全渲染后的位置
  577. optionY = doc.y + pixelToPt(8);
  578. }
  579. });
  580. // 保存该列最后一个选项的Y坐标
  581. if (i === 0) {
  582. lastOptionYPositions.column1 = doc.y;
  583. } else if (i === 2) {
  584. lastOptionYPositions.column2 = doc.y;
  585. }
  586. }
  587. }
  588. // 然后渲染问题2和4(第二行问题)
  589. if (questions.length > 1 && questions[1]) {
  590. // 问题2位于问题1的选项下方60像素处
  591. const question2Y = lastOptionYPositions.column1 + pixelToPt(75);
  592. doc.font('Helvetica-Bold')
  593. .fontSize(pixelToPt(36))
  594. .text(`2. ${questions[1].QuestionEnglish || "Question 2"}`,
  595. questionXPositions[1], question2Y, {
  596. width: pixelToPt(540),
  597. align: 'left'
  598. });
  599. // 获取问题文本渲染后的Y坐标位置
  600. const questionEndY = doc.y;
  601. // 选项起始位置 = 问题结束位置 + 20像素间距
  602. let optionY = questionEndY + pixelToPt(28);
  603. // 渲染选项
  604. const options = questions[1].OptionsEnglish || [];
  605. const optionLabels = ['A', 'B', 'C', 'D'];
  606. // 设置选项标签宽度和选项总宽度
  607. const labelWidth = pixelToPt(40); // 标签(A./B./C./D.)的宽度
  608. const totalWidth = pixelToPt(496); // 选项的总宽度
  609. const contentWidth = totalWidth - labelWidth; // 选项内容的宽度
  610. options.forEach((opt, index) => {
  611. if (index < optionLabels.length) {
  612. // 提取选项内容,移除可能存在的标签前缀
  613. let optionContent = opt.replace(/^[A-D]\.\s*/, '');
  614. // 渲染选项标签(A./B./C./D.)
  615. doc.font('Helvetica')
  616. .fontSize(pixelToPt(36))
  617. .text(`${optionLabels[index]}.`, questionXPositions[1], optionY, {
  618. width: labelWidth,
  619. align: 'left'
  620. });
  621. // 渲染选项内容,确保折行时与内容第一行对齐
  622. doc.font('Helvetica')
  623. .fontSize(pixelToPt(36))
  624. .text(optionContent, questionXPositions[1] + labelWidth, optionY, {
  625. width: contentWidth,
  626. align: 'left'
  627. });
  628. // 更新选项Y坐标,为下一个选项做准备
  629. optionY = doc.y + pixelToPt(8);
  630. }
  631. });
  632. }
  633. if (questions.length > 3 && questions[3]) {
  634. // 问题4位于问题3的选项下方60像素处
  635. const question4Y = lastOptionYPositions.column2 + pixelToPt(75);
  636. doc.font('Helvetica-Bold')
  637. .fontSize(pixelToPt(36))
  638. .text(`4. ${questions[3].QuestionEnglish || "Question 4"}`,
  639. questionXPositions[3], question4Y, {
  640. width: pixelToPt(540),
  641. align: 'left'
  642. });
  643. // 获取问题文本渲染后的Y坐标位置
  644. const questionEndY = doc.y;
  645. // 选项起始位置 = 问题结束位置 + 20像素间距
  646. let optionY = questionEndY + pixelToPt(28);
  647. // 渲染选项
  648. const options = questions[3].OptionsEnglish || [];
  649. const optionLabels = ['A', 'B', 'C', 'D'];
  650. // 设置选项标签宽度和选项总宽度
  651. const labelWidth = pixelToPt(40); // 标签(A./B./C./D.)的宽度
  652. const totalWidth = pixelToPt(496); // 选项的总宽度
  653. const contentWidth = totalWidth - labelWidth; // 选项内容的宽度
  654. options.forEach((opt, index) => {
  655. if (index < optionLabels.length) {
  656. // 提取选项内容,移除可能存在的标签前缀
  657. let optionContent = opt.replace(/^[A-D]\.\s*/, '');
  658. // 渲染选项标签(A./B./C./D.)
  659. doc.font('Helvetica')
  660. .fontSize(pixelToPt(36))
  661. .text(`${optionLabels[index]}.`, questionXPositions[3], optionY, {
  662. width: labelWidth,
  663. align: 'left'
  664. });
  665. // 渲染选项内容,确保折行时与内容第一行对齐
  666. doc.font('Helvetica')
  667. .fontSize(pixelToPt(36))
  668. .text(optionContent, questionXPositions[3] + labelWidth, optionY, {
  669. width: contentWidth,
  670. align: 'left'
  671. });
  672. // 更新选项Y坐标,为下一个选项做准备
  673. optionY = doc.y + pixelToPt(8);
  674. }
  675. });
  676. }
  677. // 问题5保持原位置不变
  678. if (questions.length > 4 && questions[4]) {
  679. const currentX = questionXPositions[4];
  680. const currentY = articleEndY + pixelToPt(130);
  681. doc.font('Helvetica-Bold')
  682. .fontSize(pixelToPt(36))
  683. .text(`5. ${questions[4].QuestionEnglish || "Question 5"}`,
  684. currentX, currentY, {
  685. width: pixelToPt(540),
  686. align: 'left'
  687. });
  688. const questionEndY = doc.y;
  689. let optionY = questionEndY + pixelToPt(28);
  690. // 渲染选项
  691. const options = questions[4].OptionsEnglish || [];
  692. const optionLabels = ['A', 'B', 'C', 'D'];
  693. // 设置选项标签宽度和选项总宽度
  694. const labelWidth = pixelToPt(40); // 标签(A./B./C./D.)的宽度
  695. const totalWidth = pixelToPt(496); // 选项的总宽度
  696. const contentWidth = totalWidth - labelWidth; // 选项内容的宽度
  697. options.forEach((opt, index) => {
  698. if (index < optionLabels.length) {
  699. // 提取选项内容,移除可能存在的标签前缀
  700. let optionContent = opt.replace(/^[A-D]\.\s*/, '');
  701. // 渲染选项标签(A./B./C./D.)
  702. doc.font('Helvetica')
  703. .fontSize(pixelToPt(36))
  704. .text(`${optionLabels[index]}.`, currentX, optionY, {
  705. width: labelWidth,
  706. align: 'left'
  707. });
  708. // 渲染选项内容,确保折行时与内容第一行对齐
  709. doc.font('Helvetica')
  710. .fontSize(pixelToPt(36))
  711. .text(optionContent, currentX + labelWidth, optionY, {
  712. width: contentWidth,
  713. align: 'left'
  714. });
  715. // 更新选项Y坐标,为下一个选项做准备
  716. optionY = doc.y + pixelToPt(8);
  717. }
  718. });
  719. }
  720. }
  721. // 14. 虚线
  722. const lastContentY = doc.page.height - pixelToPt(190);
  723. // doc.rect(pixelToPt(120), lastContentY,
  724. // pixelToPt(1630), pixelToPt(10))
  725. // .fill('#D2D2D2');
  726. doc.strokeColor('#D2D2D2')
  727. .dash(pixelToPt(20), { space: pixelToPt(28) }) // 设置虚线样式:宽20像素,间隔20像素
  728. .lineWidth(pixelToPt(10)) // 线高10像素
  729. .moveTo(pixelToPt(120), lastContentY)
  730. .lineTo(pixelToPt(120) + pixelToPt(1630), lastContentY)
  731. .stroke()
  732. .undash(); // 重置虚线样式
  733. // 15-19. 答案和底部信息
  734. doc.font('Helvetica-Bold') // 使用Helvetica-Bold作为Semibold替代
  735. .fontSize(pixelToPt(36))
  736. .fillColor('black'); // 重置颜色为黑色
  737. const answersY = doc.page.height - pixelToPt(144);
  738. // 获取问题答案
  739. const answers = [];
  740. if (questions.length > 0) {
  741. for (let i = 0; i < Math.min(questions.length, 5); i++) {
  742. const answer = questions[i].Answer || "";
  743. answers.push(`${i+1}. ${answer}`);
  744. }
  745. }
  746. // 显示答案(如果存在)
  747. const answerPositions = [120, 262, 411, 561, 711];
  748. for (let i = 0; i < Math.min(answers.length, 5); i++) {
  749. doc.text(answers[i], pixelToPt(answerPositions[i]), answersY+2, {
  750. width: pixelToPt(100),
  751. align: 'left'
  752. });
  753. }
  754. // 20-21. 应用名称
  755. doc.font('ChineseFont')
  756. .fontSize(pixelToPt(36))
  757. .text("语境背单词(微信小程序)", pixelToPt(1338), answersY,{
  758. width: pixelToPt(440),
  759. align: 'right'
  760. });
  761. // 添加二维码图片
  762. try {
  763. // 计算图片位置:距离右边120像素,距离底部100像素
  764. // 由于PDFKit使用左上角坐标系,需要计算左上角坐标
  765. const qrCodeWidth = pixelToPt(200);
  766. const qrCodeHeight = pixelToPt(200);
  767. const qrCodeX = doc.page.width - pixelToPt(120) - qrCodeWidth; // 右边距离转换为左边距离
  768. const qrCodeY = doc.page.height - pixelToPt(100) - qrCodeHeight; // 底部距离转换为顶部距离
  769. // 添加二维码图片
  770. doc.image('./public/images/acode/YJBDC_QRCode.png', qrCodeX, qrCodeY, {
  771. width: qrCodeWidth,
  772. height: qrCodeHeight
  773. });
  774. console.log("QR Code added successfully");
  775. } catch (imgError) {
  776. console.error("Error adding QR Code image:", imgError);
  777. }
  778. // 结束PDF生成
  779. doc.end();
  780. // 等待PDF生成完成
  781. const pdfBuffer = await new Promise((resolve) => {
  782. doc.on('end', () => {
  783. resolve(Buffer.concat(chunks));
  784. });
  785. });
  786. let filename="语境背单词_"+moment().format("YYMMDD_HHmm");
  787. // 设置响应头
  788. ctx.set('Content-Type', 'application/pdf');
  789. // 使用ASCII文件名作为主文件名,确保兼容性
  790. const asciiFilename = 'yjbdc_' + moment().format("YYMMDD_HHmm") + '.pdf';
  791. // 对中文文件名进行URL编码,用于filename*参数
  792. const encodedFilename = encodeURIComponent(filename + '.pdf');
  793. // 设置Content-Disposition头部,使用标准格式
  794. // 首先提供ASCII文件名,然后提供UTF-8编码的文件名
  795. ctx.set('Content-Disposition', `attachment; filename=${asciiFilename}; filename*=UTF-8''${encodedFilename}`);
  796. ctx.body = pdfBuffer;
  797. } catch (error) {
  798. console.error("Error generating PDF:", error);
  799. ctx.status = 500;
  800. ctx.body = { error: "Failed to generate PDF" };
  801. }
  802. }
  803. //生成二维码
  804. export async function BuildYJBDCQRCode(ctx) {
  805. try {
  806. // 获取微信访问令牌
  807. const tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?appid=${config.wx.yjbdc_appid}&secret=${config.wx.yjbdc_appsecret}&grant_type=client_credential`;
  808. const tokenResponse = await axios.get(tokenUrl);
  809. const tokenData = tokenResponse.data;
  810. if (!tokenData || !tokenData.access_token) {
  811. ctx.status = 400;
  812. ctx.body = { errcode: 101, errStr: '获取微信访问令牌失败' };
  813. return;
  814. }
  815. const accessToken = tokenData.access_token;
  816. // 生成小程序码
  817. const qrCodeUrl = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${accessToken}`;
  818. const path = './public/images/acode/';
  819. const imageUrl = 'YJBDC_QRCode.png';
  820. const fullPath = path + imageUrl;
  821. // 确保目录存在
  822. if (!fs.existsSync(path)) {
  823. fs.mkdirSync(path, { recursive: true });
  824. }
  825. const postData = {
  826. width: 280,
  827. scene: "SourceID=187"
  828. };
  829. // 使用axios获取二维码并保存到文件
  830. const qrCodeResponse = await axios({
  831. method: 'POST',
  832. url: qrCodeUrl,
  833. data: postData,
  834. responseType: 'stream'
  835. });
  836. // 创建写入流
  837. const writer = fs.createWriteStream(fullPath);
  838. // 将响应数据写入文件
  839. qrCodeResponse.data.pipe(writer);
  840. // 返回成功响应
  841. ctx.body = { errcode: 10000, message: "二维码生成请求已发送" };
  842. // 处理文件写入完成事件
  843. writer.on('finish', () => {
  844. console.log("二维码生成成功:", fullPath);
  845. });
  846. // 处理错误
  847. writer.on('error', (err) => {
  848. console.error("二维码文件写入失败:", err);
  849. });
  850. } catch (error) {
  851. console.error("生成二维码失败:", error);
  852. ctx.status = 500;
  853. ctx.body = {
  854. errcode: 500,
  855. errStr: '生成二维码失败',
  856. error: error.message
  857. };
  858. }
  859. }