| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240 |
- import common from '../../utils/util';
- import main from '../../utils/main';
- import constant1 from '../../utils/constant';
- Page({
- data: {
- wordList: [],
- selectedWords: [],
- difficulty: 0,
- difficulties: constant1.arrHardLevel,
- articleStyles: constant1.arrArticleStyle,
- articleStyle: '',
- generatedArticle: '',
- articleTranslation: '',
- generating: false,
- Content:"",
- },
- onLoad: function(options) {
- let that=this;
- that.setData({
- Containnerheight: main.getWindowHeight(),
- IsShowTranslate:false,
- });
- let words=options.words;
- if (!options.words)
- words="boy,girl,king,come,go,yellow,dragon,fire";
- if (words) {
- try {
- const wordList = words.split(",");
- this.setData({ wordList });
- } catch (e) {
- wx.showToast({
- title: '数据加载失败',
- icon: 'none'
- });
- }
- }
- },
- onDifficultyChange: function(e) {
- this.setData({
- difficulty: Number(e.detail.value)
- });
- },
- onArticleStyleChange: function(e) {
- this.setData({
- articleStyle: e.detail.value
- });
- console.log('选择的文章类型:', e.detail.value);
- },
- generateArticle: async function() {
- let that=this;
- if (!this.data.articleStyle) {
- wx.showToast({
- title: '请选择文章类型',
- icon: 'none'
- });
- return;
- }
- this.setData({
- generating: true,
- Content:""
- });
- try {
- let url = common.Encrypt("GenerateArticle");
- //url="https://www.kylx365.com/apiData/"+url;
- url="http://localhost:3020/api/GenerateArticle";
- let words=that.data.wordList;
- const cloudRes = await new Promise((resolve, reject) => {
- wx.request({
- url: url,
- method: "POST",
- data: {
- Words:JSON.stringify(words),
- Level:that.data.difficulty,
- Style:that.data.articleStyle
- },
- success: resolve,
- fail: reject,
- })
- });
- //console.log(cloudRes);
- let result=cloudRes.data.result.choices[0].message.content;
- console.log(result);
- let content=JSON.parse(result);
- //console.log(content);
- for(let i=0;i<content.ArticleEnglish.length;i++){
- for(let j=0;j<content.FormsOfWords.length;j++){
- let word = content.FormsOfWords[j];
- let regex = new RegExp(`\\b${word}\\b[.,!?;:]?`, 'gi');
- content.ArticleEnglish[i] = content.ArticleEnglish[i].replace(regex, match => {
- let punctuation = match.match(/[.,!?;:]$/);
- let punc = punctuation ? punctuation[0] : '';
- let wordPart = match.replace(/[.,!?;:]$/, '');
- return `<span class='highlight'>${wordPart}</span>${punc}`;
- });
- }
- }
- content.ArticleEnglishStr=content.ArticleEnglish.join("");
- for(let i=0;i<content.Question.length;i++){
- for(let j=0;j<content.Question[i].OptionsEnglish.length;j++){
- let str=content.Question[i].OptionsChinese[j];
- content.Question[i].OptionsChinese[j]=str.substr(2);
- }
- }
- this.setData({
- Content:content,
- generating: false
- });
- } catch (error) {
- console.error('生成文章失败:', error);
- wx.showToast({
- title: '生成文章失败',
- icon: 'none'
- });
- this.setData({ generating: false });
- }
- },
- showTranslate:function(e){
- this.setData({
- IsShowTranslate:!this.data.IsShowTranslate,
- })
- },
- generateTestArticle:function(e){
- this.setData({
- Content:{
- Title: "Sample Reading Article",
- ArticleEnglishStr:"This is a <span>sample</span> article for testing the PDF generation functionality.It contains multiple paragraphs and some <span>bold text</span> to test formatting.The PDF should be generated with proper layout and styling.",
- ArticleEnglish: [
- "This is a <span>sample</span> article for testing the PDF generation functionality.",
- "It contains multiple paragraphs and some <span>bold text</span> to test formatting.",
- "The PDF should be generated with proper layout and styling."
- ],
- Question: [
- {
- QuestionEnglish: "What is the purpose of this article?",
- OptionsEnglish: [
- "A. To test PDF generation",
- "B. To teach English",
- "C. To demonstrate formatting",
- "D. All of the above"
- ]
- },
- {
- QuestionEnglish: "What special formatting is used in this article?",
- OptionsEnglish: [
- "A. Italics",
- "B. Bold text",
- "C. Underline",
- "D. Strikethrough"
- ]
- }
- ]
- },
- })
- },
- //生成PDF文件
- //访问服务器的GeneratePDF接口,提交this.data.Content数据,获得一个生成好的pdf文件,服务端的代码已经生成好
- generatePDF: function(e) {
- let that = this;
- this.setData({
- generatingPDF: true,
- });
-
- let url = common.Encrypt("GeneratePDF");
- url = "https://www.kylx365.com/apiData/" + url;
- //url="http://localhost:3020/api/GeneratePDF";
- wx.request({
- url: url,
- method: "POST",
- data: {
- Content: that.data.Content
- },
- responseType: 'arraybuffer', // 确保响应类型为arraybuffer
- success: function(res) {
- // 将arraybuffer转为临时文件
- const fsm = wx.getFileSystemManager();
- const tempFilePath = `${wx.env.USER_DATA_PATH}/temp_${Date.now()}.pdf`;
-
- try {
- fsm.writeFileSync(
- tempFilePath,
- res.data,
- 'binary'
- );
- // 直接使用临时文件路径,不再尝试永久保存
- console.log('文件已生成:', tempFilePath);
-
- // 打开PDF文件预览
- wx.openDocument({
- filePath: tempFilePath,
- fileType: 'pdf',
- showMenu: true, // 显示右上角菜单,可以分享
- success: function() {
- console.log('打开文档成功');
- wx.showToast({
- title: 'PDF生成成功',
- icon: 'success'
- });
- },
- fail: function(error) {
- console.error('打开文档失败:', error);
- wx.showToast({
- title: '打开文件失败',
- icon: 'none'
- });
- }
- });
- } catch (error) {
- console.error('写入文件失败:', error);
- wx.showToast({
- title: '写入文件失败',
- icon: 'none'
- });
- }
- },
- fail: function(err) {
- console.error('请求GeneratePDF接口失败:', err);
- wx.showToast({
- title: '网络错误,请稍候重试',
- icon: 'none'
- });
- },
- complete: function() {
- that.setData({ generatingPDF: false });
- }
- });
- },
- });
|